异步任务排队调用

有多个异步任务,要按照顺序调用:任务一完成后,才触发任务二。任务二完成后,才触发任务三……

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

你可能感兴趣的:(写着玩,经验思路总结)