0

I have the following function which takes a key as parameter, then I pass this key in Rest call. The rest call gives me JSON reply and I filter out the appropriate response I need.

function getWorkflowScehmeName(projectKey){

 var restCall = AJS.params.baseURL+"/rest/projectconfig/1/workflowscheme/"+projectKey
 var workflowSchemeName

 AJS.$.get(restCall, function(response){
  if(response != null){
   workflowSchemeName = response.name
  }
  console.log(workflowSchemeName)
  return workflowSchemeName
 })
 
 return workflowSchemeName
}

Now there are multiple keys which I need to pass and need to store their appropriate responses. In the following piece of code, I'm making a list of pairTypeValues which will store the keys and the responses against them.

pairTypeValues = {}
AJS.$.each(AJS.$(".projects-list tr td:nth-child(3)"), function(index, value){
pairTypeValues[value.innerText] = getWorkflowScehmeName(value.innerText)
})

But the values in PairTypeValues are all Undefined against the their keys. How can I get the responses back and store them successfully? How do I write a callback for this?

Can anyone help, Many thanks in advance.

Tayyab Bashir
  • 111
  • 13
  • As the duplicate says, you can never return a value from an async call (as it would require time travel). Any results from an async call should be used inside the callback, or Promise-chained. In this case, you want to map the elements onto promises obtained by `$.get`, and execute them all with `$.when(...).then(...)`. Or, have `getWorkflowSchemeName` accept a callback that your inner function will pass `workflowScheduleName` to. – Amadan Sep 07 '16 at 07:33
  • Okay, thank you :) I'll give it a try like that. – Tayyab Bashir Sep 07 '16 at 07:38
  • 1
    For example: `function getWorkflowSchemeName(projectKey, callback){... if (response != null) { callback(response.name); } ... };` then you can do `getWorkflowSchemeName(value.innerText, function(workflowSchemeName) { pairTypeValues[value.innerText] = workflowSchemeName; })` – Amadan Sep 07 '16 at 07:39
  • Thanks for reply. That's exactly what I was looking for. Now I'm getting back the response from the call back but they are being sorted. For example I passed keys (C, B, A) in this order But the values are being stored in A B C order. – Tayyab Bashir Sep 07 '16 at 12:54
  • Async doesn't care about order. If you want order, impose it yourself (e.g. by using that `index`). – Amadan Sep 08 '16 at 00:36

0 Answers0