2016-10-05 66 views
-1

我需要使用promise爲數組中的每個項目執行函數。我希望promise.all適合這個。但是,函數執行的其餘部分應該在數組中的任何項的終止時(函數執行失敗)繼續執行。 promise.all的行爲是這樣嗎?使用promise爲陣列中的每個元素執行函數

示例:在下面的代碼片段中,需要爲每個項目parallely執行函數getInfo,並且當getInfo(item1)的結果在可用時返回,而不等待結果爲可用於item2 & item3。而且,發生錯誤對任何項目應該不會影響項目的其餘部分的執行數組中

var arrayIterate = [item1, item2, item3] 

function getInfo(item){ 
    // do stuff 
}; 
+2

'Promise.all'不執行功能。它等待着多重承諾。 – Bergi

回答

1

不promise.all以這種方式運行。但是您可以通過回調手動鏈接功能。

就這樣

for(i=0;i<arr.length;i++){ myFunction('param1', function(){ }); }

myFunction(param1, callback){ if(error){ callback() }else{ //do something and then callback() } }

這樣即使您的代碼獲取出錯也不會停止在這一點上,但將執行在陣列中的所有元素。

PS:但請記住for loop不應該在這裏使用,因爲它不會等待回調。因此,使用遞歸技術來對陣列的每個元素執行函數執行。

1

Promise.all()是完美的。

比方說,你有一個網址列表,你想從這些網址獲取數據。

var request = require('request-promise') // The simplified HTTP request client 'request' with Promise support. Powered by Bluebird. 

var Promise = require('bluebird'); 

var urls = ["a-url", "some-other-url"]; 

var promises = []; 

// You create the promise for each url and push them in an array 

urls.forEach(function(url){ 
    promises.push(request.get(url)); 
}); 

// After that you can call the Promise.all() on this promises array and get the results. 

Promise.all(promises).then(function(results) { 
    // results is an array of results from all the urls 

    // No error encountered 

    // Celebrate victory 

}).catch(function(err) { 
    // Even if one error occurs, it will come here and won't execute any further. 
    // Handle error 

}); 

你甚至可以去Promise.map()

來吧,閱讀文檔青鳥:http://bluebirdjs.com/docs/getting-started.html

相關問題