In a nutshell: Promises allow us to solve the “callback hell” problem by chain-calling, especially in asynchronous processes, and Promise to keep code clean and readable.
First, the use of promises
var foo = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("success")}, 1000); console.log("Make a Promise"); }) foo.then((res) => { console.log(res) }).catch((err) => { console.log(err); }) // Output: create a Promise successCopy the code
Here is an example of a promise, and the output reads, “Create a Promise”, and after a 1000ms delay, “success” is printed.
As you can see from the examples above, promises are convenient for handling asynchronous operations. In addition, promises can be invoked chained.
Ii. Promise/A+ specification
(1) A promise must have three states: Pending, disappointingly (resolved) and Rejected.
When you are in the pending state, you can switch to the regrettable or Rejected state. When you are in a regrettable state or the rejected state, there is no change.
(1) A promise must have a THEN method, which accepts two parameters: PROMISE. Then (onFulfilled,onRejected)
The onFulfilled method represents the method to be executed when the state changes from Pending — >fulfilled(resolved)
OnRejected indicates the method whose state is executed from pending — > Rejected.
Iii. Fulfill the Promise in accordance with the Promise/A+ specification
function myPromise(constructor){
let that=this;
that.status="pending"That. Value =undefined; That. Reason =undefined; // Define the state of the rejected statefunction resolve(value){
if(that.status==="pending"){
that.value=value;
that.status="resolved"; }}functionReject (reason){// Two === ="pending", ensuring that the change in state is irreversibleif(that.status==="pending"){
that.reason=reason;
that.status="rejected"; Constructor (resolve,reject); }catch(e){ reject(e); }}Copy the code
myPromise.prototype.then=function(onFullfilled,onRejected){
let that=this;
switch(that.status){
case "resolved":
onFullfilled(that.value);
break;
case "rejected":
onRejected(that.reason);
break;
default:
}
}
Copy the code