有时候我不希望所有动作一起发生,而是按照一定顺序,逐个进行

 var promise=doSomething();
promise=promise.then(doSomethingElse);
promise=promise.then(doSomethingElse2);
promise=promise.then(doSomethingElse2);

// forEach 实现

 function queue(things){
let promise=Promise.resolve();
things.forEach(element => {
promise=promise.then(()=>{
return new Promise(resolve=>{
setTimeout(() => {
console.log(element)
resolve('ok');
}, 1000);
});
})
});
}
queue(['h1','h2','h3']);

// reduce 实现

 function queue2(things) {
let promise = Promise.resolve();
things.reduce(function (totel, item) {
return totel.then(() => {
return new Promise(resolve => {
setTimeout(() => {
console.log('reduce', item)
resolve('ok');
}, 1000);
});
});
}, promise)
}
queue2(['h1', 'h2', 'h3']);

  

04-19 19:46