Handwritten promise principle series eight: encapsulation of Promise.all method, usage of Promise.all

Insert image description here

Hello friends, the "Handwritten Promise Principles Series" is coming to an end soon, and I plan to end it with "Handwritten Promise Principles Series 9".

Why come out in Series 9? Probably because of the number nine! In traditional Chinese culture, "ten" is the number of abundance. Things will turn to the extreme and decline when they reach their peak, so we should treat it with caution; and "nine" is a step forward for a hundred feet, and we hope that we can climb to a hundred feet. Go one step further. Nine is also the number of poles and the number of yang; in the Book of Changes, the yang line (yao) uses nine, the yin line uses six, and the Qian hexagram is composed of six yang lines. The "Elephant Biography" defines the Qian hexagram as : Heaven moves vigorously, and a gentleman strives to constantly strive for self-improvement.

Let’s digress and get back to the topic.

The current chapter discusses the usage and encapsulation of the Promise.all method.

From the definition of the word all, we can know that it means 全部. In fact, the result is returned only when all promise objects are successfully executed. As long as one fails, It returns a failed result.

Let’s first look at the failed call method:

let p1 = new Promise((resolve, reject) => {
    
    
	resolve("111");
});
let p2 = Promise.reject("222"); // 改变状态为失败 reject
let p3 = Promise.resolve("333");
let result = Promise.all([p1, p2, p3]); // 参数为 promise 对象组成的数组
console.log(result);

Insert image description here
The parameter of the Promise.all method is an array of promise objects. When there is a failure status in the parameters of the Promise.all method, the status and result of the current failed promise object are directly returned.

Let’s look at the calling method for successful synchronous execution:

let p1 = new Promise((resolve, reject) => {
    
    
	resolve("111");
});
let p2 = Promise.resolve("222");
let p3 = Promise.resolve("333");
let result = Promise.all([p1, p2, p3]);
console.log(result);

Insert image description here

There is also a calling method for successful asynchronous execution:

let p1 = new Promise((resolve, reject) => {
    
    
	setTimeout(()=>{
    
    
		resolve("111");
	}, 1000)
});
let p2 = Promise.resolve("222");
let p3 = Promise.resolve("333");
let result = Promise.all([p1, p2, p3]);
console.log(result);

Insert image description here
It can be seen from the above synchronous and asynchronous calling methods that no matter whether the promise object changes state synchronously or asynchronously, the execution result of Promise.all is ordered. Why is this? p1–>p2–>p3. But the displayed result is p2–>p3–>p1 is an asynchronous task and is executed at the end. The execution order of the three of them should be "222"、"333"、"111", because . Normally, when executed asynchronously, the result should be resolve("111")

In fact, the key point is how to make the execution results of Promise.all orderly when changing the state asynchronously? It's very simple, here uses the array subscript assignment method , arr[1] = "222"; arr[2] = "333"; arr[0] = "111". The result obtained in this way must be in order ["111", "222", "333"], because when the assignment operation is performed based on the array subscript, it has nothing to do with the execution order of the code.

let arr = new Array(3);  // 创建 length 为3的空数组 arr
arr[1] = 222;
console.log(arr);
arr[2] = 333;
console.log(arr);
arr[0] = 111;
console.log(arr);

Insert image description here

Code encapsulated by Promise.all method:

Promise.all = function(promiseArray){
    
    
	return new Promise((resolve, reject) => {
    
    
		// 定义 Promise.all 方法的返回值
		let arr = [];
		// 循环处理 promise 对象
		for(let i = 0; i < promiseArray.length; i++){
    
    
			let p = promiseArray[i];
			// 调用每一个 promise 对象的 then 方法,获取结果
			p.then((value) => {
    
    
				// 根据数组下标赋值,保证 promise 对象返回正确的结果
				arr[i] = value;
				// 判断是否所有的 promise 对象都执行完毕,若全部执行完毕,则返回结果
				if (arr.length === promiseArray.length) {
    
    
					resolve(arr);
				}			
			}, reason => {
    
    
				// 状态变为失败时,直接返回结果
				reject(reason);
			})
		}
	})
}

Guess you like

Origin blog.csdn.net/ThisEqualThis/article/details/129499025