【问题标题】:Resolving a promise multiple times多次履行承诺
【发布时间】:2014-06-04 19:32:21
【问题描述】:

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

构建我自己的 Promise 版本还是有其他方法?

【问题讨论】:

标签: javascript promise rsvp-promise


【解决方案1】:

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

然而,这项任务似乎也可以通过承诺来完成。只是不要对一组 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) 获得对结果的承诺,另请参阅 https://github.com/tildeio/rsvp.js#arrays-of-promises

【讨论】:

  • 是的,你可以用http_module2做同样的事情
  • 你的意思是有另一种方法而不是 http_module2 返回地图承诺?
  • 不,http_module2 会返回对超链接结果的承诺,不是吗?也许您也应该发布它的代码,以便我也可以将其包含在我的答案中。
  • http_module1http_module2 的实现基本相同。他们从前一个承诺的响应中获取一个密钥并发出一个 HTTP 请求。一旦 http 请求完成,他们resolve 承诺。
  • 我本可以添加代码,但我仍在考虑它的实现。只有在我知道如何使用它们的情况下才能最终确定。
【解决方案2】:

您可以编写函数来返回您的 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

【讨论】:

  • 对不起,我不太明白你的解决方案。
  • 我的解决方案是/曾经 - 只解决你需要的那些承诺,因为你需要它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 2016-11-07
  • 2015-11-16
  • 2016-06-05
  • 2016-06-17
相关资源
最近更新 更多