新的async/await语法可以轻松实现。
const sleep = time=>new Promise(resolve=>setTimeout(resolve,time));
(async function(){
for(let i=0;i<10;i++){
await sleep(1000);
console.log(i);
}
})()
如果要只想用ES6的话,也可以的,用生成器yield代替,并且写个自动run的辅助函数。
const next = (gen,val) => {
const n = gen.next(val);
!n.done && Promise.resolve(n.value).then(d=>next(gen,d));
}
const run = genfunc => next(genfunc());
const sleep = time=>new Promise(resolve=>setTimeout(resolve,time));
run(function* (){
for(let i=0;i<10;i++){
yield sleep(1000);
console.log(i);
}
})
如果是ES5的话,只能创造一个数组,然后在异步函数里不停的调用next来传递顺序,常用node的人应该对express的next不陌生吧。
function run(arr,func){
var len = arr.length;
function next(){
if(!len) return;
func(arr[arr.length-len],next);
len--;
}
next();
}
var arr = Array.apply(null, {length: 10}).map(Function.call, Number);
run(arr,function(i,next){
setTimeout(function(){
console.log(i);
next();
},1000);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…