What is Promise?
Promise English translation means promise, promise. Its function is like the Chinese meaning, it is a promise.
MDN's explanation: The
Promise object is a proxy object (a value is proxied), and the value of the proxied object may be unknown when the Promise object is created. It allows you to bind corresponding processing methods (handlers) for the success and failure of asynchronous operations. This allows asynchronous methods to return values like synchronous methods, but instead of returning the final execution result immediately, it is a promise object that can represent future results.
Having said so much, it actually translates into a vernacular:
1. The daughter-in-law is hungry and needs to eat, so I want to go to the street to buy food ( asynchronous method )
2. She doesn't know when I will come back after buying the food (the asynchronous method will execute for a few seconds ) ,
3. But after buying the food and returning home, I will make a braised pork ribs for my daughter-in-law to eat ( after the asynchronous method is executed, the return value needs to be processed ).
What should I do at this time, I will use a promise: just
say this thing Give it to me, I promise that I will go shopping, I will make you braised pork ribs as soon as I finish buying it, and I will call you to eat it as soon as it is done (this place is equivalent to a promise chain call ), what are you doing now? You can play games with Douyin ( does not affect the calling of other codes ).
A Promise has the following states:
pending: initial state, neither a successful nor a failed state (I went out to buy food, you wait for me to come back)
fulfilled: means the operation is successfully completed. (After buying the food, go home and tell my daughter-in-law that I have the food you want to eat)
rejected: It means the operation failed. (I didn’t get any food, why don’t you order a takeaway)
A Promise object in the pending state may change to a fulfilled state and pass a value to the corresponding state processing method, or it may change to a failed state (rejected) and pass failure information. When either of these situations occurs, the handlers bound to the then method of the Promise object will be called.
The then method contains two parameters: onfulfilled and onrejected, both of which are of type Function. When the Promise status is fulfilled, the onfulfilled method of then is called, and when the Promise status is rejected, the onrejected method of then is called, so there is no competition between the completion of the asynchronous operation and the binding processing method).
Look at a basic example:
new Promise((resolve, reject) => {
console.log('code begin !');
let num = 4;
// 假装执行一个异步方法
setTimeout(() => {
console.log('async begin !');
num += 2;
// 把Promise状态设为fulfilled,并把结果传递出去
resolve(num);
// 把Promise状态设为rejected,并把失败信息传递出去
//reject('promise被手动中止');
// throw 'uncaught exception!'; // 这里要注意,catch无法捕获在异步方法里抛出的异常
}, 1000);
}).then((result) => { // 当Promise的状态被设为接受(fulfilled)时执行
console.log('fulfilled :' + result);
}, (reason) => { // 当Promise的状态被设为拒绝(rejected)时执行
console.log('rejected :' + reason);
}).catch((error) => {
console.log('error :' + error);
}).finally(() => {
// do something !
});
The then method returns a Promise. It requires at most two parameters: the callback function for the success and failure of the Promise.
The catch method is executed when an exception occurs during the execution, or the Promise status is set to failed (rejected), and the rejected execution function is not set. In addition, catch cannot catch exceptions thrown in asynchronous methods
The finally method does not receive any parameters in the finally callback function because it cannot know the final state of the promise. It is only used in the case of execution regardless of the final result.
In addition, Promises can be called in a chain. If the execution of the then method ends and a new Promise is returned, the then methods will be executed in sequence. But here is one thing to note: if an exception occurs in the call chain or the status is changed to rejected, then the rest of the call chain will not be executed. So be careful when using chain calls!
Code example:
new Promise((resolve, reject) => {
console.log('code begin !');
let num = 4;
setTimeout(() => {
console.log('num + 2 = 6');
num += 2;
resolve(num);
}, 1000);
}).then((num) => {
return new Promise((resolve, reject) => {
console.log('num * num = 36');
setTimeout(() => {
num *= num;
resolve(num);
}, 1000);
});
}).then((num) => {
return new Promise((resolve, reject) => {
console.log('num + num = 72');
setTimeout(() => {
num += num;
resolve(num);
}, 1000);
});
}).then((result) => {
console.log('fulfilled :' + result);
}, (reason) => {
console.log('rejected :' + reason);
}).catch((error) => {
console.log('error :' + error);
}).finally(() => {
// do something !
});
Promise has some other methods such as Promise.all( iterable ): you can pass an iterable (similar to an array) into it, it will wait for all the promises in the iterable to be executed and return uniformly . The returned result is also an array, which will follow The order of the promises within the parameters is not determined by the order in which the promises are called.
Promise.all([mothod1(), mothod2()])
.then((result) => {
console.log('all complete');
console.log(result);
});
function mothod1() {
console.log('first mothod');
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('mothod1 complete');
}, 2000);
});
}
function mothod2() {
console.log('second mothod');
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('mothod2 complete');
}, 1000);
});
}
Promise.race( iterable ): You can pass an iterable (similar to an array) into it. Once a promise in the iterable is resolved or rejected, the promise will be resolved or rejected.
Promise.race([mothod1(), mothod2()])
.then((result) => {
console.log(result);
console.log('complete');
});