0

I'm working with a string of XMLHttpRequests that each depend on the one prior to it. Psuedocode:

xhr1.open('GET', 'http://foo.com');
xhr1.onload = function(e){
  xhr2.open('POST', xhr1.response.url)
  xhr2.onload = function(e){
    xhr3.open('GET', xhr2.response.url2);
    xhr3.onload = function(e){
      console.log('hooray! you have data from the 3rd URL!');
    }
    xhr3.send();
  }
  xhr2.send();
}
xhr1.send();

Is this the kind of situation where using promises would be a good idea to avoid all the callback muck?

NoR
  • 975
  • 1
  • 7
  • 8

2 Answers2

2

Yes. If you return a promise in a then, the next chained then listens for that promise instead of resolving from the original promise. Given that ajaxCall returns a promise, your code will then look like:

ajaxCall(1)
.then(function(result1){
  return ajaxCall(2);
})
.then(function(result2){
  return ajaxCall(3);
})
.then(function(result3){
  // all done
});

// Sample AJAX call
function ajaxCall(){
  return new Promise(function(resolve, reject){
    // xhr code. call resolve/reject with accordingly
    // args passed into resolve/reject will be passed as result in then
  });
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

Yes, definitively. Assuming a helper function like those from How do I promisify native XHR?, your code could be transformed into

makeRequest('GET', 'http://foo.com').then(function(response1) {
    return makeRequest('POST', response1.url);
}).then(function(response2) {
    return makeRequest('GET', response2.url2);
}).then(function(response3) {
    console.log('hooray! you have data from the 3rd URL!');
});

Still callbacks of course, but no more nesting required. Also you'd have simple error handling, and the code looks much cleaner (partially contributed to by the non-promise-related fact of abstracting XHR in its own function).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375