This is the sixth day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021.
Definition 1.
Promise objects, used to represent the final completion (or failure) of an asynchronous operation and its resulting value, are a more reasonable and powerful solution to asynchrony than traditional solutions (callbacks and events). ES6 has written it into the language standard, unifying usage, and providing native Promise objects.
A Promise object represents a value that is not necessarily known at the time the Promise is created, and can associate the eventual success return value or failure reason of an asynchronous operation with the appropriate handler. Instead of immediately returning the final value, the asynchronous method returns a Promise.
A Promise must be in one of the following states:
pending
: Initial state, not honored, not rejectedfulfilled
: The operation is completerejected
: Rejected, operation failed
2. Basic usage
The instantiation of a Promise is accomplished with the new operator, passing in a function as an argument. The Promise state is private and can only be manipulated internally. In the function passed in, the state transition that controls the Promise is done by calling its two function arguments, usually named resolve() and Reject (). Calling resolve() converts the state to pity, and calling Reject () converts the state to Rejected. Also, calling Reject () throws an error.
The following code instantiates a Promise using the new operator, passing in a function with two arguments: resolve() and reject(). Control the state transitions of promises through simple judgments. Obviously, after the current code executes, you should call resolve(), which translates the state to depressing.
After the Promise, the THEN method is called, and the THEN method accepts at most two functions as parameters. The first parameter is the callback function whose state becomes fulfilled, and the second parameter is the callback function whose state becomes Rejected. In this case, because the Promise state has become depressing, the then method executes the first parameter and prints out the value from the resolve() method: ‘depressing’.
new Promise((resolve, reject) = > {
const a = 1;
if (a === 1) {
resolve('fulfilled');
} else {
reject('rejected');
}
}).then(
fulfilledValue= > console.log(fulfilledValue),
rejectedValue= > console.log(rejectedValue)
);
// fulfilled
Copy the code
If you change a slightly so that the Promise state changes to Rejected, the then method takes the second argument, printing out the reject() value: ‘Rejected’.
new Promise((resolve, reject) = > {
const a = 2;
if (a === 1) {
resolve('fulfilled');
} else {
reject('rejected');
}
}).then(
fulfilledValue= > console.log(fulfilledValue),
rejectedValue= > console.log(rejectedValue)
);
// rejected
Copy the code
In addition, if an error is thrown internally, the then method also executes a second function:
new Promise((resolve, reject) = > {
throw 'error';
}).then(null.error= > console.log(error));
// error
Copy the code
3. Prototype approach
1. Promise.prototype.then()
The then() method returns a new Promise, which, as mentioned above, takes up to two arguments: the Promise’s success and failure callback functions. Because a Promise can only transition state once, the two functions must be mutually exclusive.
The THEN method supports chained calls.
Returns a new Promise if the callback function in THEN:
(1) If a value is returned, then the Promise returned by then is the fulfilled state, and the returned value will be the parameter value of the callback function of the fulfilled state.
As the code shows, the initial Promise state is depressing. Then the first THEN method calls the first callback function, printing 1 and returning ‘Jack’. Then the Promise returned by this then is also a depressing state. And takes ‘Jack’ as the callback argument to the second then method.
new Promise((resolve, reject) = > {
resolve(1);
// reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
return 'Jack';
})
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// fulfilledValue 1
// fulfilledValue Jack
Copy the code
This will be a pity state. If the first THEN method calls its second callback function, which returns ‘Jack’, which is a value, then the then returns the fulfilled state. And the returned value is taken as the parameter value of the callback function of the depressing state, which is completely consistent with the rule above.
new Promise((resolve, reject) = > {
// resolve(1);
reject(-1);
})
.then(
value= > {
console.log('fulfilledValue', value);
},
value= > {
console.log('rejectedValue', value);
return 'Jack';
}
)
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// rejectedValue -1
// fulfilledValue Jack
Copy the code
As you can see, the rules for returning promises are the same no matter which callback the then method calls. For convenience, the initial promises below are set to a depressing state.
(2) If no value is returned, the Promise returned by then is a depressing state, and the parameter value of the callback function of the depressing state is undefined.
As shown in the following code, the first callback function of the second THEN takes undefined because the first THEN returns no value.
new Promise((resolve, reject) = > {
resolve(1);
// reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
})
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// fulfilledValue 1
// fulfilledValue undefined
Copy the code
(3) This is a pity state. The Promise returned by THEN is the Rejected state, and the error will be the parameter value of the callback function of the fulfilled state.
new Promise((resolve, reject) = > {
resolve(1);
// reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
throw 'Error! ';
})
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// fulfilledValue 1
// rejectedValue Error!
Copy the code
(4) Return a Promise that is a depressing state, then the Promise returned is a depressing state, and the callback function parameters of the former Promise acceptance state will be regarded as the callback function parameters of the returned Promise acceptance state.
As follows, the first THEN returns a fulfilled Promise, and the second then calls the first callback with the parameter ‘depressing’.
new Promise((resolve, reject) = > {
resolve(1);
// reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
return Promise.resolve('fulfilled');
})
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// fulfilledValue 1
// fulfilledValue fulfilled
Copy the code
(5) Return a Promise from the Rejected state, then return a Promise from the Rejected state, and return the callback function parameter of the rejected state.
new Promise((resolve, reject) = > {
resolve(1);
// reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
return Promise.reject('rejected');
})
.then(
res= > {
console.log('fulfilledValue', res);
},
res= > {
console.log('rejectedValue', res); });// fulfilledValue 1
// rejectedValue rejected
Copy the code
(6) Return a Promise that is in a pending state, then return a Promise that is also in a pending state, and its final state is the same as that of the previous Promise. At the same time, it becomes the same callback argument that was executed in the final state as the Promise was executed in the final state.
(7) If the original Promise is rejected and the first THEN does not have a second parameter, then the second then executes its second callback, with parameters in reject from the original Promise.
new Promise((resolve, reject) = > {
// resolve(1);
reject(-1);
})
.then(value= > {
console.log('fulfilledValue', value);
})
.then(null.res= > {
console.log('rejectedValue', res);
});
// rejectedValue -1
Copy the code
2. Promise.prototype.catch()
The promise.prototype.catch () method is used to add a rejection handler to a Promise. This method accepts only one parameter: the onRejected handler. It behaves the same as calling promise.prototype. then(undefined, onRejected).
Here’s the code, two equivalent ways of writing it.
new Promise((resolve, reject) = > {
reject('error');
}).catch(error= > console.log(error));
// error
Copy the code
new Promise((resolve, reject) = > {
reject('error');
}).then(null.error= > console.log(error));
// error
Copy the code
3. Promise.prototype.finally()
Promise. Prototype. Finally add () method is used to Promise onFinally handler, the handler when converting Promise fulfilled or rejected state will be executed. But the onFinally handler doesn’t know whether the Promise state is fulfilled or Rejected, so this method is mostly used to add cleanup code.
new Promise((resolve, reject) = > {
console.log('loading start... ');
const a = 2;
if (a === 1) {
resolve(1);
} else {
reject(-1);
}
})
.then(value= > {
console.log('fulfilled value', value);
})
.catch(error= > console.log('error', error))
.finally(() = > console.log('loading end... '));
// loading start...
// error -1
// loading end...
Copy the code
4. Instance methods
1. Promise.all()
The promise.all () method takes input of an iterable type of Promise and returns only one instance of Promise, the result of which is an array of all the Promise’s resolve callbacks. In simple terms, promise.all () is used to wrap multiple Promise instances into a new Promise instance.
const promiseArray = [1.2.3.4].map(item= > new Promise(resolve= > resolve(item)));
console.log(promiseArray);
// [ Promise { 1 }, Promise { 2 }, Promise { 3 }, Promise { 4 } ]
Promise.all(promiseArray).then(res= > console.log(res));
// [1, 2, 3, 4]
Copy the code
2. Promise.race()
The promise.race (iterable) method returns a Promise that will be accepted or rejected once one of the promises in the iterator is accepted or rejected.
const promiseArray = [1.2.3.4].map(item= > new Promise(resolve= > resolve(item)));
console.log(promiseArray);
// [ Promise { 1 }, Promise { 2 }, Promise { 3 }, Promise { 4 } ]
Promise.race(promiseArray).then(res= > console.log(res));
/ / 1
Copy the code
3. Promise.resolve()
The promise.resolve () method returns a Promise object that accepts the state.
Promise.resolve(1).then(res= > console.log(res));
/ / 1
Copy the code
4. Promise.reject()
The promise.reject () method returns a Promise object with a reject state with parameters.
Promise.reject(-1).then(null.res= > console.log(res));
// -1
Copy the code
The above is my learning income, if there is anything wrong, welcome to point out the exchange!
Reference:
- JavaScript Advanced Programming (Version 4)
- “The MDN”