大佬教程收集整理的这篇文章主要介绍了Node JS Promise.all和forEach,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
then
链通常最多为1层深。Promise.all
比一个接一个地执行要好-每个等待都在下一个执行之前要好。
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we Now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I saID, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the prevIoUs
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// Now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
我有一个类似结构的数组,它公开了异步方法。异步方法调用返回数组结构,从而返回更多异步方法。我正在创建另一个JSON对象来存储从该结构获得的值,因此我需要注意跟踪回调中的引用。
我已经编写了一个蛮力解决方案,但是我想学习一个更惯用或干净的解决方案。
这是一些部分代码-
var jsonItems = [];
items.forEach(function(item){
var jsonItem = {};
jsonItem.name = item.name;
item.getThings().then(function(things){
// or Promise.all(allItemGetThingCalls,function(things){
things.forEach(function(thing,indeX){
jsonItems[index].thingName = thing.name;
if(thing.type === 'file'){
thing.getFile().then(function(filE){ //or promise.all?
jsonItems[index].filesize = file.getSize();
以上是大佬教程为你收集整理的Node JS Promise.all和forEach全部内容,希望文章能够帮你解决Node JS Promise.all和forEach所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。