Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

javascript - ES6 Promises - something like async.each?

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.

Edit 1

per request, here is an example:

Assume this code:

let model1 = new MongooseModel({prop1: "a", prop2: "b"});
let model2 = new MongooseModel({prop1: "c", prop2: "d"});

let arr = [model1 , model2];

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();
})

My question is: with ES6, can I do it natively? without the NPM 'async' package?

Edit 2

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();
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For those who like short answers:

[func1, func2].reduce((p, f) => p.then(f), Promise.resolve());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...