NoR
NoR

Reputation: 995

Is this a good use case for using Promises?

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?

Upvotes: 0

Views: 500

Answers (2)

Bergi
Bergi

Reputation: 664196

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).

Upvotes: 1

Joseph
Joseph

Reputation: 119827

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
  });
}

Upvotes: 2

Related Questions