简体   繁体   中英

Resolving a promise multiple times

I am building a module using Promises , where I make multiple http calls on multiple urls , parse the responses and then again make more http calls.

c = new RSVP.Promise({urls:[]}) //Passing a list of urls
c.then(http_module1) // Call the http module
.then(parsing_module) // Parsing the responses and extract the hyperlinks
.then(http_module2) // Making http requests on the data produced by the parser before.
.then(print_module) // Prints out the responses.

The problem is that - If I use a promise, I can not parse the modules unless all the http requests are made. This is because - Once a promise has been resolved or rejected, it cannot be resolved or rejected again.

Build my own version of promises or is there an alternate approach?

You can write functions that return handles to your promises and create reusable parts that are still chainable. For example:

function getPromise(obj){
   return new RSVP.Promise(obj);
}
function callModule(obj){
   return getPromise(obj).then(http_module1);
}

var module = callModule({urls:[]})
  .then(getFoo())
  .then(whatever());

  //etc

There are libraries that support such kind of pipes/streams, you don't need to build such yourself.

Yet the task seems to be doable with promises as well. Just don't use a single promise for an array of urls, but multiple promises - one for each url:

var urls = []; //Passing a list of urls
var promises = urls.map(function(url) {
    return http_module1(url) // Call the http module
      .then(parsing_module) // Parsing the responses and extract the hyperlinks
      .then(http_module2) // Making http requests on the data produced by the parser before.
      .then(print_module); // Prints out the responses.
});

This will run all of them in parallel. To wait until they have ran, use RSVP.all(promises) to get a promise for the results, see also https://github.com/tildeio/rsvp.js#arrays-of-promises

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM