有多个异步任务,要按照顺序调用:任务一完成后,才触发任务二。任务二完成后,才触发任务三……
const arr = ['emily', 'nancy', 'haha'];
let index = 0;
function greeting(name) {
return new Promise(resolve => {
const time = Math.random() * 5000
setTimeout(() => {
resolve({ name, time });
}, time);
});
};
function next() {
greeting(arr[index]).then(o => {
console.log(o);
index++;
if (index <= arr.length - 1) {
next();
}
})
}
next();