Who knows how much Promise falls?

Who knows how much Promise falls?

  • Promise series navigation
  • Preface
  • 1. Promise.all()
    • 1. Grammar
    • 2. Code and description
      • (1) Code segment
      • (2) Code segment
      • (3) Code segment
      • (4) Code segment
  • 2. Promise.any()
    • 1. Grammar
    • 2. Code and description
      • (1) Code segment
      • (2) Code segment
  • 3. Promise.race()
    • 1. Grammar
    • 2. Code and description
      • (1) Code segment
      • (2) Code segment
      • (3) Code segment
      • (4) Code segment
      • (5) Code segment
  • 4. Promise.allSettled()
    • 1. Grammar
    • 2. Code and description
      • (1) Code segment
      • (2) Code segment
  • Summarize

Promise series navigation

1. Promise is essentially a game of drumming and passing flowers.
2. Promise four-style drumming
3. Promise spreads flowers by beating drums
4. Who knows how much Promise will fall?


Foreword

Record learning results in order to review the past and learn the new

  1. The Promise series of articles is a preparation for learning VUE, so it is classified into the VUE series. According to MDN’s description, it should be a “JavaScript standard built-in object”, hereby explained.
  2. The Promise series of articles is mainly about learning the experience and experience of Promise in MDN, MDN address.

Let’s take a look at MDN’s description first.

Promise.all() MDN instructions:

The Promise.all() static method accepts a Promise iterable as input and returns a Promise. When all input Promises have been honored, the returned Promise will also be honored (even if an empty iterable is passed in), and an array containing all the fulfilled values will be returned. If any of the input Promises were rejected, the returned Promise will be rejected with the first rejection reason.

Promise.any() MDN instructions:

The Promise.any() static method takes as input a Promise iterable and returns a Promise. When any of the input Promise is fulfilled, the returned Promise will be fulfilled and the first fulfilled value will be returned. When all input Promises are rejected (including when an empty iterable is passed), it is rejected with an AggregateError containing an array of rejection reasons.

Promise.race() MDN instructions:

The Promise.race() static method accepts a promise iterable as input and returns a Promise. This returned promise will be finalized as the first promise is finalized.

Promise.allSettled() MDN instructions:

The Promise.allSettled() static method takes as input an iterable of Promise objects and returns a single Promise. When all input Promises have been finalized (including when an empty iterable is passed in), the returned Promise will be honored with an array of objects describing the results of each Promise.

MDN makes it very clear that the four methods are all static methods. The input parameter is a Promise iterable object and the return is a single Promise. They are promise concurrent methods.

This topic is called “Who knows how much”, where “whose flower falls” refers to the finalization of the Promise object, whether it will be honored or rejected; “how much” is the concept of quantity. If all are honored, the first one to reject will The first object is the concept that any one is finalized and all are finalized.

1. Promise.all()

1. Grammar

Promise.all(iterable)

Parameter Description:

iterable is an iterable object such as Array or String.

return value:

  • Already fulfilled if the passed iterable is empty.
  • Asynchronously fulfilled if all promises in the given iterable have been fulfilled. The redemption value is an array whose elements are ordered in the same order as the passed promise, not in the order of the time of redemption. If the incoming iterable is a non-empty but does not contain a pending promise, the returned promise will still be fulfilled asynchronously rather than synchronously.
  • Asynchronously rejected if any promise in the given iterable is rejected. The rejection reason is the rejection reason for the first rejected promise.

2. Code and description

The hard truth.

(1) Code segment

const p1 = Promise.resolve(1);
const p2 = 2;
const p3 = new Promise((resolve, reject) => {<!-- -->
setTimeout(() => {<!-- -->
resolve("Wei Zi");
}, 100);
});

Promise.all([p1, p2, p3]).then((values) => {<!-- -->
console.log(values);
});

operation result:

MDN says:

Promise.all waits for the results of all fulfillments (or the first rejection).

This is more to the point, and is more concise and clear than the long speech before.

(2) Code segment

 // All values are not Promise, so the returned Promise will be honored
const p1 = Promise.all([1, 2, 3]);
// The only Promise in the input has already been honored, so the returned Promise will be honored
const p2 = Promise.all([4, 5, 6, Promise.resolve(7)]);
// One (and only) input Promise was rejected, so the returned Promise will be rejected
const p3 = Promise.all([8, 9, 10, Promise.reject(11)]);

console.log(p1);
console.log(p2);
console.log(p3);

// Using setTimeout, we can execute code after the queue is empty
setTimeout(() => {<!-- -->
console.log("The queue is now empty");
console.log(p1);
console.log(p2);
console.log(p3);
});

operation result:

This code finally has a rejection.

(3) Code segment

Going back to the original code, when we wanted to get the return, we considered that we might get multiple pictures at once.

html2canvas(this.$refs.imgBox, {<!-- -->
  height: this.$refs.imgBox.scrollHeight,
  width: this.$refs.imgBox.scrollWidth,
}).then((canvas) => {<!-- -->
  canvas.toDataURL("image/png")
});

Now let’s simulate it again:

//Main tone
function test(){<!-- -->
const p1 = Promise.all([getImg(), getImg(), getImg()]);
console.log(p1);
\t
setTimeout(() => {<!-- -->
console.log("The queue is now empty");
console.log(p1);
});
}

function getImg(){<!-- -->
return new Promise((resolve, reject) => {<!-- -->
setTimeout(() => {<!-- --> resolve("Wei Zi") }, 1000);
}).then(() => {<!-- --> return "image/png"; });
}

operation result:

I feel a little taller…

(4) Code segment

const p1 = Promise.all([]);
\t\t\t
console.log(p1);

operation result:

It’s boring to pass an empty array just to see the results.

2. Promise.any()

1. Grammar

Promise.any(iterable)

Parameter Description:

An iterable of promises (such as an array).

return:

  • Already rejected if the passed iterable is empty.
  • Asynchronously fulfilled (asynchronously fulfilled), when any Promise in the given iterable is fulfilled, the returned Promise will be fulfilled. Its redemption value is the redemption value of the first Promise to be honored.
  • asynchronously rejected, when all Promises in the given iterable have been rejected. The rejection reason is an AggregateError whose errors property contains an array of rejection reasons. Regardless of completion order, these errors are ordered in the order of incoming Promises. If the passed iterable is non-null but does not contain a pending Promise, the returned Promise is still rejected asynchronously (rather than rejected synchronously).

2. Code and description

The hard truth.

(1) Code segment

const pErr = new Promise((resolve, reject) => {<!-- -->
reject("always fails");
});

const pSlow = new Promise((resolve, reject) => {<!-- -->
setTimeout(resolve, 500, "finally completed");
});

const pFast = new Promise((resolve, reject) => {<!-- -->
setTimeout(resolve, 100, "will be completed soon");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {<!-- -->
console.log(value);
// pFast is the first to cash out
});

operation result:

The running result is as MDN said:

Promise.any() will honor the first Promise that is fulfilled, even if a Promise is rejected first.

(2) Code segment

const failure = new Promise((resolve, reject) => {<!-- -->
reject("always fails");
});

Promise.any([failure, Promise.reject("Yao Huang")]).catch((err) => {<!-- -->
console.log(err);
});

operation result:

The running result is as MDN said:

If no Promise is fulfilled, Promise.any() will reject with an AggregateError.

It turned out to be rejected by the drastic method of throwing an exception. It seems that the errors attribute was not found.

3. Promise.race()

1. Grammar

Promise.race(iterable)

Parameter Description:

iterable is a promise iterable object (such as an array).

return value:

A Promise will be finalized asynchronously with the status of the first finalized promise in the iterable. In other words, if the first finalized promise is fulfilled, then the returned promise will also be fulfilled; if the first finalized promise is rejected, then the returned promise will also be rejected. If the incoming iterable is empty, the returned promise will remain pending. If the incoming iterable is non-empty but none of the promises in it are pending, the returned promise will still be finalized asynchronously (rather than finalized synchronously).

2. Code and description

The hard truth.

(1) Code segment

function sleep(time, value, state) {<!-- -->
  return new Promise((resolve, reject) => {<!-- -->
    setTimeout(() => {<!-- -->
if (state === "Cash") {<!-- -->
return resolve(value);
} else {<!-- -->
return reject(new Error(value));
}
    }, time);
  });
}

const p1 = sleep(500, "One", "Cash");
const p2 = sleep(100, "two", "cash");

Promise.race([p1, p2]).then((value) => {<!-- -->
console.log(value); // "two"
// Both will be honored, but p2 is faster
});

const p3 = sleep(100, "三", "Cash");
const p4 = sleep(500, "four", "reject");

Promise.race([p3, p4]).then(
  (value) => {<!-- -->
    console.log(value); // "three"
    // p3 is faster, so it honors
  },
  (error) => {<!-- -->
    // will not be called
  }
);

const p5 = sleep(500, "五", "Cash");
const p6 = sleep(100, "六", "Reject");

Promise.race([p5, p6]).then(
  (value) => {<!-- -->
    // will not be called
  },
  (error) => {<!-- -->
    console.error(error.message); // "Six"
    // p6 is faster, so it rejects
  }
);

operation result:

The running results are as stated in the comments.

(2) Code segment

// Pass in an array of resolved Promise to trigger Promise.race as soon as possible.
const resolvedPromisesArray = [Promise.resolve("Wei Zi1"), Promise.resolve("Wei Zi2")];

const p = Promise.race(resolvedPromisesArray);
//Print the value of p immediately
console.log(p);

// Using setTimeout, we can execute code after the stack is empty
setTimeout(() => {<!-- -->
console.log("The stack is now empty");
console.log(p);
});

operation result:

According to MDN, this code is based on asynchronicity.

(3) Code segment

const foreverPendingPromise = Promise.race([]);
console.log(foreverPendingPromise);
setTimeout(() => {<!-- -->
console.log("The stack is now empty");
console.log(foreverPendingPromise);
});

operation result:

It’s boring to pass an empty array, just to verify what MDN said:

An empty iterable causes the returned Promise to remain pending.

(4) Code segment

const foreverPendingPromise = Promise.race([]);
const alreadyFulfilledProm = Promise.resolve(100);

const arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"];
const arr2 = [foreverPendingPromise, "Non-Promise value", Promise.resolve(100)];
const p = Promise.race(arr);
const p2 = Promise.race(arr2);

console.log(p);
console.log(p2);
setTimeout(() => {<!-- -->
console.log("The stack is now empty");
console.log(p);
console.log(p2);
});

operation result:

You can experience the various flavors of this code by yourself.

(5) Code segment

const data = Promise.race([
  fetch("/api"),
  new Promise((resolve, reject) => {<!-- -->
    //Reject after 5 seconds
    setTimeout(() => reject(new Error("Request timeout")), 5000);
  }),
])
.then((res) => res.json())
.catch((err) => displayError(err));

This code is very useful for reference.

4. Promise.allSettled()

1. Grammar

Promise.allSettled(iterable)

Parameter Description:

iterable is an iterable object (such as Array) composed of promises.

return value:

  • Already fulfilled, if the passed iterable is empty.
  • Asynchronously fulfills when all promises in the given iterable have been finalized (either fulfilled or rejected). The value fulfilled is an array of objects describing the outcome of each promise in the order of the promises passed in the iterable, regardless of the order of completion.

2. Code and description

The hard truth.

(1) Code segment

Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));

operation result:

The running result is as MDN said:

Each result object has the following properties:

status: a string, either “fulfilled” or “rejected”, indicating the final status of the promise.
value: Exists only if status is “fulfilled”. The value of the promise fulfilled.
reason: Exists only when status is “rejected”, the reason for promsie rejection.

(2) Code segment

const p = Promise.allSettled([]);
\t\t\t
console.log(p);

setTimeout(() => {<!-- -->
console.log("The stack is now empty");
console.log(p);
});

operation result:

Carrying boredom to the end is also a state.

Summary

This is the end of the entire Promise series. Now I will summarize the entire series: four strikes, three passes and four knowledges.