Promise static method summary

Keywords: Javascript Front-end ECMAScript

Promise.resolve

The Promise.resolve() method returns a promise object parsed with the given value. If the value is a promise, the promise will be returned; If the value is thenable (i.e. with "then" method), the returned promise will "follow" the thenable object and adopt its final state.

const thenable = {
  then(onFullfilled, onRejected) {
    onFullfilled("thenable");
    throw new Error("error thenable"); // It will not change to the rejected state
  }
};
const errorThenable = {
  then(onFullfilled, onRejected) {
    throw new Error("error thenable");
    onFullfilled("thenable"); // It will not change to the fullfilled state
  }
};
//The parameter is null
Promise.resolve().then(function(value) {
  console.log(value);    //undefined
});
//Parameter is not thenable
Promise.resolve("string").then(function(value) {
  console.log(value);    //"string"
});
//The parameter is fullfilled thenable
Promise.resolve(thenable).then(function(value) {
  console.log(value);    //"thenable"
});
//The parameter is rejected thenable
Promise.resolve(errorThenable).catch(function(value) {
    console.log(value);  //"error thenable"
})
//The parameter is Promise
Promise.resolve(new Promise(function(resolve) {
  resolve("Promise");
})).then(function(value) {
  console.log(value);    //"Promise"
});

Promise.reject

The Promise.reject() method returns a Promise object with a rejection reason.

Promise.all

Promise.all() method receives the input of a promise's iterable type (Note: Array, Map and Set all belong to the iterable type of ES6), and returns only one promise instance;   The result of the resolve callback of Promise.all is an Array. The resolve callback of promise is executed when all the resolve callbacks of the input promise end or there is no promise in the input iterable. Its reject callback execution is that as long as the reject callback of any input promise is executed or an illegal promise is input, an error will be thrown immediately, and the reject is the first error message thrown.

const p1 = Promise.resolve(3);
const p2 = 1337;
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

// Wait for all to complete, or return after any of them fails.
Promise.all([p1, p2, p3]).then(values => {
  console.log(values); // [3, 1337, "foo"]
});

Promise.all(0).catch(err => {
    console.log(err) // TypeError: number 0 is not iterable
});

Promise.allSettled (ES11)

The Promise.allSettled() method returns a promise in the fully completed state after all given promises have been completed (whether fully or rejected), with an object array, and each object represents the corresponding promise result.
Array type: {status: string, value: any}.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).then((results) => console.log(results));

// [{
//     status: "fulfilled",
//     value: 3
// }, {
//     statues: "rejected",
//     reason: "foo"
// }]

Promise.race

The Promise.race(iterable) method returns a   Promise: once a promise in iterable is resolved or rejected, the returned promise will be resolved or rejected. If the passed iterable is empty, the returned promise will wait forever. If the iteration contains one or more uncommitted values or resolved / rejected commitments, then   Promise.race   Resolves to the first value found in the iteration.

var p1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, "one");
});
var p2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, "two");
});
Promise.race([p1, p2]).then(function(value) {
  console.log(value); // "two"
  // Both are done, but p2 is faster
});


var p3 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, "three");
});
var p4 = new Promise(function(resolve, reject) {
    setTimeout(reject, 500, "four");
});
Promise.race([p3, p4]).then(function(value) {
  console.log(value); // "three"
  // p3 is faster, so it's done
}, function(reason) {
  // Not called
});


var p5 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, "five");
});
var p6 = new Promise(function(resolve, reject) {
    setTimeout(reject, 100, "six");
});
Promise.race([p5, p6]).then(function(value) {
  // Not called
}, function(reason) {
  console.log(reason); // "six"
  // p6 was faster, so it failed
});
const raceArr = [22, Promise.resolve(33), Promise.resolve(44)];

// Because 22 is a non Promise value, 22 is returned
Promise.race(raceArr).then(val => console.log(val)); // 22

Promise.any (ES12)

Promise.any() receives a promise iteratable object, as long as one of the promises   If successful, return the successful promise  . If there is no promise in the iteratable object   Success (i.e. all   promises   Both fail / reject), it returns a failed instance of promise and AggregateError types, which is a subclass of Error and is used to collect single errors together. In essence, this method and Promise.all() The opposite is true.

// Success
const pErr = new Promise((resolve, reject) => {
  reject("Always fail");
});

const pSlow = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, "Final completion");
});

const pFast = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "Finish soon");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {
  console.log(value); // Finish soon
})



// Failure condition
const pErr = new Promise((resolve, reject) => {
  reject('Always fail');
});

Promise.any([pErr]).catch((err) => {
  console.log(err);
})
// Expected output: "AggregateError: No Promise in Promise.any was resolved"

Posted by pabs1983 on Tue, 09 Nov 2021 04:05:52 -0800