[ES6 knowledge] Promise object

1.1 Overview

PromiseObject used to represent the final completion (or failure) of an asynchronous operation and its result value. It is a solution to asynchronous programming (which can solve the callback hell problem).

An Promiseobject represents a proxy whose value is not necessarily known when the promise is created. It allows you to associate the final success return value or failure reason of an asynchronous operation with the corresponding handler. This allows asynchronous methods to return values ​​like synchronous methods: the asynchronous method does not return the final value immediately, but returns a promise to hand the value to the user at some time in the future.

Native JavaScriptScipt case collection
JavaScript + DOM basic
JavaScript basic to advanced
Canvas game development

A Promisemust be in one of the following states:

  • Pending : Initial status, neither honored nor rejected.
  • Fulfilled : means the operation was completed successfully.
  • Rejected : means the operation failed.

Promise objects only have state changes: from pending to fulfilled and from pending to rejected. As long as it is fulfilled and rejected, the status will not change anymore, that is, resolved (finalized).

Once a Promise object is created, it will be executed immediately and cannot be canceled midway.

img

We can use the Promise.prototype.then(), Promise.prototype.catch()and Promise.prototype.finally()these methods to associate further actions with a promise that becomes finalized.

For example, .then()the method requires two parameters, the first parameter is a callback function that handles the cashed status, and the second parameter is a callback function that handles the rejected status. Each .then()method also returns a newly generated promise object, which can be used as a chain of calls, like this:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

myPromise
  .then(value => { return value + ' and bar'; })
  .then(value => { return value + ' and bar again'; })
  .then(value => { return value + ' and again'; })
  .then(value => { return value + ' and again'; })
  .then(value => { console.log(value) })
  .catch(err => { console.log(err) });

If there is no urgent need, you can .catch()perform error handling in the last statement, which is simpler. Prematurely handling a promise that becomes rejected will have an impact on subsequent promise chain calls, unless we need to handle the error immediately, for example, some type of error must be thrown outside to pass the error status in the chain call . .

1.2 Static methods

Promise.all()and Promise.race()are two combined tools for running asynchronous operations in parallel.

  • Promise.all(iterable)This method returns a new promise object and waits until all promise objects succeed or any promise fails. If all promises succeed, it will use an array containing the return values ​​​​of all promises in the iterable as the return value of the success callback. The order is consistent with the order of iterable. Once any promise object in the iterable fails, the new promise will be rejected immediately based on the reason that the promise object failed.
  • Promise.race(iterable)Wait until the status of any promise changes to finalized. When any child promise in the iterable parameter succeeds or fails, the parent promise will immediately use the child promise's success return value or failure details as parameters to call the corresponding processing function bound to the parent promise and return the promise object.
const p1 = getCmpData("basicSetting");
var p2 = null;
if (that.isOnlineForm) {
	p2 = getCmpData("formDesign");
} else {
	p2 = new Promise(function (resolve, reject) {
        resolve(null);
    });
}
const p3 = getCmpData("processDesign");

Promise.all([p1, p2, p3])
.then((res) => {
  const param = {};
  this.sendToServer(param); //接口调用传参
})
.catch((err) => {//错误信息处理
  err.target && (this.activeStep = err.target);
  err.msg && this.$message.warning(err.msg);
});
  • Promise.allSettled(iterable)Wait until all promises have been finalized (each promise has been fulfilled or rejected). Returns a promise that is fulfilled after all promises have been finalized and an array of objects corresponding to the results of each promise.
  • Promise.any(iterable)Receives a collection of promise objects, and when any one of the promises succeeds, the value of the successful promise is returned.

Promise.resolve()and Promise.reject()are shortcut methods for manually creating a Promise that has been resolved or rejected. They are sometimes useful.

  • Promise.reject(reason)Returns an object with status rejected Promiseand passes the given failure information to the corresponding handler function.
  • Promise.resolve(value)Returns an object whose state is determined by the given value Promise. If the value is thenable (that is, thenan object with a method), the final status of the returned Promise object is determined by the execution result of the then method; otherwise, the status of the returned Promise object is fulfilled, and the value is passed to the corresponding then method. .
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
.then(result3 => { /* use result3 */ });

In general, if you don't know whether a value is a promise object, use Promise.resolve(value)to return a Promise object so that the value can be used as a promise object.

1.3 Instance methods

  • Promise.prototype.then()Add a callback function for the fulfilled and rejected status of the promise, which fulfills the promise with the return value of the callback function. If the fulfilled or rejected status is not handled (for example, onFulfilledor onRejectedis not a function), the value at the time the promise was finalized is returned.
  • Promise.prototype.catch()Add a rejected callback function to the promise and return a new promise. If the callback function is called, its return value will be honored, otherwise the value of the original promise will be honored.
  • Promise.prototype.finally()Add a callback function to the promise and return a new promise. This new promise will be fulfilled when the original promise is fulfilled. The callback function passed in will be called when the original promise is finalized (whether it is honored or rejected).

1.4 Promise rejection event

When a Promise is rejected, one of the two events described below is dispatched to the global scope (usually, if windowused in a web worker, or Workerother worker-based interface). The two events are as follows:

  • rejectionhandledrejectThis event is dispatched when a Promise is rejected and after the function handles the rejection.
  • unhandledrejectionrejectThis event is dispatched when a Promise is rejected but no function is provided to handle the rejection.

In the above two cases, PromiseRejectionEventthe event has two attributes, one is promisethe attribute, which points to the rejected Promise, and the other is the reason(en-US) attribute, which is used to explain the reason why the Promise was rejected.

window.addEventListener("unhandledrejection", event => {
  /* 你可以在这里添加一些代码,以便检查
     event.promise 中的 promise 和
     event.reason 中的 rejection 原因 */

  event.preventDefault();
}, false);

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/133375528
Recommended