Usage of AP.request

add-on
jira-plugin
atlassian-connect
jira-cloud

#1

Is AP.request synchronous/asynchronous? If synchronous how can I turn it to false(asynchronous) or vice-versa?


#2

Updated answer

I have just learned that AP.request already returns a promise. So you can just:

const myResponse = await AP.request('/rest/api/3/mypermissions');

Original answer

AP.request is asynchronous. You could wrap it in a promise and then use async / await to emulate synchronous behaviour.

For example:

new Promise((resolve, reject) => {
  AP.request('/rest/path/to/api', {
    success: function(responseText){
      resolve(responseText);
    },
    error: function(xhr, statusText, errorThrown){
       reject(arguments);
    }
  })
});

See: https://developer.atlassian.com/cloud/jira/platform/jsapi/request/


#3

Hi @rmassaioli,

How can I code this using JavaScript? I have tried as below, but doesn’t work as expected(using AP.request on each loop).

async function start() {
	var myResponse = await AP.request({
		url: '/rest/api/2/issue/issueId',
		type: 'PUT',
		data: dataStr,
		contentType: 'application/json',
		success: function (response) {},
		error: function (response) {}
	});
}
start();

#4

I don’t think you should have the success or error callbacks specified.


#5

Hi @rmassaioli,

Thanks, I have changed the code simply with url within AP.request as below and its working for a GET method.

async function start() {
   var myResponse = await AP.request('/rest/api/2/issue/issueId');
}
start();

But doesn’t work for POST method. So, how can I process data using POST method?


#6

Hi @rmassaioli,

We couldn’t get any idea or solution for this issue. Can you direct how to solve this issue?


#7

Hi @hariprasath, did you try this?

var myResponse = await AP.request({
		url: '/rest/api/3/issue/issueId',
		type: 'POST',
		data: dataStr
});

#8

Hi @piskunovigorm,

Yes, I tried out. But it throws an error - Uncaught SyntaxError: await is only valid in async function.


#9

@hariprasath, it’s true. You need to specify async function in order to use await expression. Did you try like this?

async function start() {
   var myResponse = await AP.request({
		url: '/rest/api/3/issue/issueId',
		type: 'POST',
		data: dataStr
  });
}
start();

#10

Hi @piskunovigorm,

Yes, it worked! The values get saved, but the success/error block hits only at end and not each time when the request is processed.


#11

AP.request() executes an XMLHttpRequest as a Promise, so there is no need to use success/error blocks. Try then() and catch() instead.

async function start() {
   var myResponse = await AP.request({
		url: '/rest/api/3/issue/issueId',
		type: 'POST',
		data: dataStr
  })
  .then(data => alert(data.body))
  .catch(e => alert(e.err));;
}
start();