Promise notes
introduce
A Promise is an object that represents the final completion or failure of an asynchronous operation. Essentially, a Promise is an object returned by a function to which we can bind a callback function, so that we don't need to pass the callback function as an argument in the first place.Copy the code
convention
When you use promises, you have the following conventions:
- The callback is not called until the current event loop is complete.
- Callback functions added via THEN () are called even after the asynchronous operation has completed (successfully or failed).
- Multiple callbacks can be added by calling THEN () multiple times, and they are executed in the order they were inserted.
state
A Promise must be in one of the following states:
- Pending: The initial state that has neither been granted nor rejected.
- This is a big pity: this will be fulfilled successfully.
- Rejected: Indicates that the operation fails.
Chain calls
/** It is a common requirement to perform two or more asynchronous operations in a row, following the success of the previous operation, to start the next operation with the results of the previous operation. We can implement this requirement by creating a Promise chain. * /
new Promise((resolve, reject) = > {
resolve('略');
})
.then(res= > {
res += '略';
return res;
})
.then(res= > {
res += '略';
return res;
})
.then(res= > {
console.log(res); / / have slightly
})
// Note: The callback must have a return value, otherwise it will not get the result of the previous Promise.
// If you use the arrow function, () => x than () => {return x; } is more concise, but the latter retains the return notation to allow multiple statements.
The promise.prototype. then and promise.prototype. catch methods return promises, so they can be called chained.
Copy the code
Catch’s subsequent chain operation
/** It is possible to continue a chain operation after a failed callback. This can be used with a catch, which is useful for doing a new operation after throwing a failed callback. * /
// For example:
new Promise((resolve, reject) = > {
console.log('Open your eyes! ');
resolve();
})
.then(() = > {
console.log('Take the first step in the morning! ');
})
.then(() = > {
throw new Error('And then it broke! ');
})
.catch(err= > {
console.error(err.message);
console.log('Get treatment! ');
})
.then(() = > {
console.log('Move on to step two! ');
})
Copy the code
combination
Promise.resolve() and promise.reject () are shortcuts to manually create a resolve or reject Promise. Promise.all() and promise.rece () are two combinatorial tools that run asynchronous operations in parallel.Copy the code
The sequential
/** To avoid surprises, functions passed to then() will always be called asynchronously, even if a Promise has changed to the resolve state
Promise.resolve().then(() = > console.log('the evening! '))
console.log('in the morning! ');
// Print the result
/ / in the morning!
/ / evening!
The function passed to then() is placed in a microtask queue rather than executed immediately, which means it starts executing */ after all runtimes of the JavaScript event queue have ended and the event queue has been emptied
Copy the code
The constructor
Promise()
Create a new Promise object. This constructor is primarily used to wrap functions that have not yet added promise support.Copy the code
A static method
Promise.all(iterable)
This method returns a new promise that will succeed only if all of the iterable promise objects succeed, or if any of the iterable promise objects fail. The new Promise object, after firing the success state, returns the success callback with an array of all the promise returns from iterable, in the same order as the iterable. If the new Promise triggers a failed state, it treats the error message from the first promise in iterable that triggers a failed state as its failed error message. The promise.all method is often used to process sets of states for multiple Promise objects.Copy the code
Promise.allSettled(iterable)
This is a big pity. By the time all promises are finalized, each promise will be fulfilled or rejected. Return a promise that completes after all promises have completed. With an array of objects, each corresponding to the result of each promise.Copy the code
Promise.any(iterable)
Receive a collection of Promise objects, and if a Promise succeeds, return the value of that successful PromiseCopy the code
Promise.race(iterable)
When any child promise in the Iterable argument succeeds or fails, the parent promise immediately calls the parent promise's binding handle using the child promise's success return value or failure details as arguments and returns the promise object.Copy the code
Promise.reject(reason)
Return a Promise object with a failed state and pass the given failure information to the corresponding handler.Copy the code
Promise.resolve(value)
Returns a Promise object whose state is determined by the given value. If the value is thenable (that is, the object with the THEN method), the final state of the returned Promise object is determined by the then method execution. Otherwise (for example, if the value is empty, basic type, object with no THEN method), the Promise object will be returned with the state of FULFILLED and the value will be passed to the corresponding THEN method. If you don't know if a value is a Promise object, you can use promise.resolve (value) to return a Promise object so that the value can be used as a Promise object.Copy the code
Promise the prototype
attribute
Promise.prototype.constructor
Returns the created instance function, which defaults to the Promise functionCopy the code
function
Promise.prototype.catch(onRejected)
Add a rejected callback to the current Promise, which returns a new promise. When this callback function is called, the new Promise will be resolved with its return value. Otherwise, if the current promise enters the fulfilled state, the fulfilled result of the current promise will be the fulfilled result of the new promise.Copy the code
Promise.prototype.then(onFulfilled, onRejected)
Add the fulfillment and rejection callback to the current promise, returning a new promise that resolves with the return value of the callbackCopy the code
Promise.prototype.finally(onFinally)
Add an event-handling callback to the current Promise object and return a new promise object after the original promise object has resolved. The callback will be invoked after the current Promise is fulfilled or failed. This is a big pity.Copy the code
Basic use of Promise
// The Promise object is created by the keyword new and its constructor
// Accept two functions resolve and reject
// Successful callback and failed callback
const promise = new Promise((resolve, reject) = > {
// Make some operational judgments here, and eventually call one of the following:
resolve(); // fulfilled
/ / or
reject(); // rejected
});
Copy the code