The latest to see a more interesting interview question:

How do I serial implement promises?

Here is a brief introduction to the solution. Natively provides all and Race methods for several Promise methods. However, they are not executed sequentially. So how do you do serial methods? Here are two ways to write it:

Recursive implementation

Pass the next asynchronous method recursively inside the then method: then(next())

function iteratorPromise(arr){

	(function iter() {if(arr.length)
			arr.shift()().then(iter)
	})()
}

let arr = [()=>{
	return new Promise(res=>{
		console.log("run", Date.now());
		res()
	})
},()=>{
	return new Promise(res=>{
		console.log("run", Date.now());
		res()
	})
},()=>{
	return new Promise(res=>{
		console.log("run", Date.now());
		res()
	})
}]

iteratorPromise(arr);

// output
run 1529918098567
run 1529918098568
run 1529918098569
Copy the code

Cycle call

Use promise.resolve () instead. Through the loop assignment, get the final result.

function iteratorPromise(arr){

	letres = Promise.resolve(); Arr. ForEach (fn = > {res = res., then (() = > fn ()) / / key is res = res. Then... This logic})}let arr = [()=>{
	return new Promise(res=>{
		setTimeout(()=>{
			console.log("run", Date.now());
			res()
		},1000)
		
	})
},()=>{
	return new Promise(res=>{
		setTimeout(()=>{
			console.log("run", Date.now());
			res()
		},1000)
		
	})
},()=>{
	return new Promise(res=>{
		setTimeout(()=>{
			console.log("run", Date.now());
			res()
		},1000)
		
	})
}]

iteratorPromise(arr);


// output
run 1529918643573
run 1529918644574
run 1529918645580
Copy the code