簡體   English   中英

多次解決承諾

[英]Resolving a promise multiple times

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

建立我自己的承諾版本還是有另一種方法?

您可以編寫返回承諾句柄的函數,並創建可鏈接的可重用部分。 例如:

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,而是使用多個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.
});

這將並行運行所有這些。 要等到它們運行,請使用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