Promise chain and static method


The combination of multiple contracts can form powerful code logic. This combination can be
achieved in two ways: contract linkage and contract synthesis

One, Promise chain

Each Promise method returns a new Promise object, and the new Promise has its own method so that the Promise chain can be realized

let p = new Promise((resolve, reject) => {
    
    
    console.log('first');
    resolve();
});
 p.then(() => console.log('second'))
  .then(() => console.log('third'))
  .then(() => console.log('fourth'));
// first
// second
// third
// fourth

A series of synchronous tasks are implemented, but this is not an asynchronous chain. To truly execute asynchronous tasks, you can make each executor return an instance of a contract, so that other handlers will wait for it to be settled. Get its result (result)

Example:

    let p = new Promise((resolve, reject) => {
    
    
        console.log('1');
        setTimeout(resolve, 1000);
    });
    p.then(() => new Promise((resolve, reject) => {
    
    
        console.log('2');
        setTimeout(resolve, 1000);
    }))
    .then(() => new Promise((resolve, reject) => {
    
    
        console.log('3');
        setTimeout(resolve, 1000);
    }));

    //1 (1秒后)
    //2 (2秒后)
    //3 (3秒后)

The Promise chain just solves the callback hell problem, and then(), catch(), finally() all return Promises, which can be serialized at the same time

Two, Promise synthesis

1. Promise.all()

This static method receives an iterable object (usually an array) and returns a new contract

  1. When all the given promises are settled, the new promise will be resolved, and the result array will become the result of the new promise
let p = Promise.all([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
  new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
  new Promise(resolve => setTimeout(() => resolve(3), 1000))  // 3
]);
console.log(p); // Promise <pending>

p.then(()=>{
    
    console.log(p)}); // Promise <fulfilled> <value>:[1,2,3] 当上面这些 promise 准备好时:每个 promise 都贡献了数组中的一个元素

Note that the order of the elements in the result array is the same as the order in the source promise. Even though the first promise took the longest time to resolve, it is still the first in the result array. (In order of iterator)

  1. If at least one of the included futures is pending, the resulting futures will also be pending.
let p1 = Promise.all([new Promise(() =>
{
    
    })]);// 永远pending

let p2 = Promise.all([
Promise.resolve(),
Promise.reject(),
Promise.resolve()
]);
  1. If any promise is rejected, the promise returned by Promise.all will be rejected immediately with this error

let p =Promise.all([
  new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
  new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
  new Promise((resolve, reject) => setTimeout(() => (console.log('test');reject(3)), 3000))
]).catch(alert); // Error: Whoops!

//test

The second Promise is rejected, and the reason for rejection is used as the reason for Promise.all rejection (Error: 3). Promises that are rejected
afterwards will not affect the final Promise.all reason, but will run normally (output test, silently handle reject(3) ) There will be no unhandled errors)

2. Promise.allSettled

If any promise rejects, Promise.all will be rejected as a whole. It is useful for this "all or nothing" situation when we need all results to be successful:

Promise.all([
  fetch('/template.html'),
  fetch('/style.css'),
  fetch('/data.json')
]).then(render); // render 方法需要所有 fetch 的数据

ps. This language is new to ES2020, and old browsers need to use polyfill

3. Promise.race()

Similar to Promise.all, but only wait for the first settled promise and get its result (or error)

// 解决先发生,超时后的拒绝被忽略
let p1 = Promise.race([
Promise.resolve(3),
new Promise((resolve, reject) =>
setTimeout(reject, 1000))
]);
setTimeout(console.log, 0, p1); // Promise <resolved>: 3

Similar to Promise.all(), the Promise after the first settled will be executed normally, and all reject operations will be processed silently.

三、Promise.resolve/reject

In addition to the executor function for settled, the following two static methods can also be used for settled: (not much used)

1. Promise.resolve()

Promise.resolve(value) creates a resolved promise with the result value.
The following two are equal

let p1 = new Promise((resolve, reject) =>
resolve());
let p2 = Promise.resolve();

2. Promise.reject()

Promise.reject(error) uses error to create a rejected promise.

Four, Promise static method summary

The Promise class has 5 static methods:

  1. Promise.all(promises)-When waiting for all promises to be resolved, return an array of their results. If any one of the given promises is rejected, then it will become the error of Promise.all, and the results of all other promises will be ignored.
  2. Promise.allSettled(promises) (ES2020 new method)-When waiting for all promises to be settled, return their results in the form of an object array containing the following:
    • status: “fulfilled” 或 “rejected”
    • value (if fulfilled) or reason (if rejected).
  3. Promise.race(promises)-Wait for the first settled promise, and use its result/error as the result.
  4. Promise.resolve(value) —— Create a resolved promise with the given value.
  5. Promise.reject(error)-Create a rejected promise with the given error.

Guess you like

Origin blog.csdn.net/S_aitama/article/details/110825773