多次解决承诺

时间:2014-04-20 17:27:08

标签: javascript promise rsvp-promise

我正在使用Promises构建模块,我在多个网址上进行多次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.

建立我自己的承诺版本还是有替代方法?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

有些图书馆支持这种管道/流,您不需要自己构建这样的管道。

然而,这项任务似乎也可以兑现承诺。只是不要使用单个承诺来获取一系列网址,但是多个承诺 - 每个网址一个:

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)获取结果承诺,另请参阅https://github.com/tildeio/rsvp.js#arrays-of-promises