简体   繁体   English

多次解决承诺

[英]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. 我正在使用Promises构建一个模块,我在多个URL上进行多个http调用,解析响应然后再次进行更多的http调用。

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. 问题是 - 如果我使用promise,除非发出所有http请求,否则我无法解析模块。 This is because - Once a promise has been resolved or rejected, it cannot be resolved or rejected again. 这是因为 - 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: 只是不要为一个url数组使用单个promise,而是使用多个promises - 每个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 要等到它们运行,请使用RSVP.all(promises)来获得结果的承诺,另请参阅https://github.com/tildeio/rsvp.js#arrays-of-promises

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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