user10933121
user10933121

Reputation:

How should I nest these async calls?

Within my code I have a function that depends on the result of an async call to an API endpoint. In order for the function to execute properly it needs to wait for the result of the call. So I've read up on async calls and from another Stack Overflow question I read that you should make use of callback functions to enable correct execution.

The code below is my attempt to make use of callbacks to allow my function to run successfully, but it doesn't work and at the moment I think the calls are messed up.

I'm not sure how I need to structure this code, but I first need the getInstructionType() call to return its value, then the GetValidationResult() call to return its value, and then the setValidationRowColor() function needs to execute.

getInstructionType(applicationNumber, function(result) {
  getInstructionValidationResult(applicationNumber, function(type) {
    setValidationRowColor(result);
  });
});

function getInstructionValidationResult(applicationNumber) {
  var url = //-snip-;
  $.get(url, function(data) {
    return data;
  });
}

function getInstructionType(applicationNumber) {
  var url = //-snip-;
  $.get(url, function(data) {
    return data;
  });
}

Upvotes: 0

Views: 36

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55663

The alternative to callbacks (which are completely valid) are promises - which is really just another form or callbacks. Assuming you are using jQuery's $.get, you are already making use of Promises:

getInstructionType(applicationNumber, function(result) {
  return getInstructionValidationResult(applicationNumber)
    .then(function() {
      setValidationRowColor(result)
    })
});

function getInstructionValidationResult(applicationNumber) {
  var url = //-snip-;
  return $.get(url)
}

function getInstructionType(applicationNumber) {
  var url = //-snip-;
  return $.get(url)
}

Note that all I did was return the $.get and added a .then which accepts your callback inside getInstructionType

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337610

You could add arguments to the functions which you can use as callbacks. Then you can call those when the AJAX request completes, something like this:

getInstructionType(applicationNumber, function(result) {
  getInstructionValidationResult(applicationNumber, function(type) {
    setValidationRowColor(result);
  });
});

function getInstructionValidationResult(applicationNumber, callback) {
  $.get(/*-snip-*/, function(data) {
    // some custom logic to work with the response here...
    callback && callback(data);
  });
}

function getInstructionType(applicationNumber, callback) {
  $.get(/*-snip-*/, function(data) {
    // some custom logic to work with the response here...
    callback && callback(data);
  });
}

Upvotes: 1

Related Questions