ES6 Promises - 类似于 async.each? [英] ES6 Promises - something like async.each?
问题描述
试图弄清楚如何找到功能与 async.eachSeries 完全一样的东西,我需要一个按顺序(不是并行)运行的异步操作列表,但找不到在原生 ES6 中执行此操作的方法,可以有没有人指教一下?
Trying to figure-out how to find something that functional exactly like async.eachSeries, i need a list of async actions run in sequence (not in parallel) but can't find a way to do it in native ES6, can anyone advise, please?
附言考虑过发电机/产量,但还没有经验,所以我没有意识到它到底能帮我什么.
p.s. thought about generators/yield but don't have the experience yet so I'm not realized how exactly it can help me.
编辑 1
每个请求,这里是一个例子:
per request, here is an example:
假设代码如下:
let model1 = new MongooseModel({prop1: "a", prop2: "b"});
let model2 = new MongooseModel({prop1: "c", prop2: "d"});
let arr = [model1 , model2];
现在,我想连续运行它,而不是并行运行,所以使用异步"NPM 很容易:
Now, I want to run over it in a series, not parallel, so with the "async" NPM it's easy:
async.eachSeries(arr, (model, next)=>{
model.save.then(next).catch(next);
}, err=>{
if(err) return reject(error);
resolve();
})
我的问题是:使用 ES6,我可以在本地实现吗?没有 NPM 'async' 包?
My question is: with ES6, can I do it natively? without the NPM 'async' package?
编辑 2
使用 async/await 可以轻松完成:
With async/await it can be done easily:
let model1 = new MongooseModel({prop1: "a", prop2: "b"});
let model2 = new MongooseModel({prop1: "c", prop2: "d"});
let arr = [model1 , model2];
for(let model of arr){
await model.save();
}
推荐答案
对于喜欢简短回答的人:
For those who like short answers:
[func1, func2].reduce((p, f) => p.then(f), Promise.resolve());
这篇关于ES6 Promises - 类似于 async.each?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!