2016-10-05 65 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

相关问题