多次解决承诺



我正在使用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.

问题是——如果我使用promise,我就无法解析模块,除非所有的http请求都被发出。这是因为-Once a promise has been resolved or rejected, it cannot be resolved or rejected again.

建立我自己的承诺版本,或者有其他方法吗?

您可以编写函数来返回promise的句柄,并创建仍然可链接的可重用部分。例如:

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

有些库支持这种类型的管道/流,您不需要自己构建。

然而,有了承诺,这项任务似乎也是可行的。只是不要对一组url使用单个promise,而是使用多个promise-每个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.
});

这将并行运行所有这些操作。要等到它们运行完毕,请使用RSVP.all(promises)获得结果的promise,另请参阅https://github.com/tildeio/rsvp.js#arrays-承诺的

最新更新