JavaScript: Promise combinator

If it can be achieved, remember to like and share, thank you~

Insert image description here

Promises are not a new concept in JavaScript. They are objects that represent the eventual completion or failure of an asynchronous operation and its result value.

Promise has three possible states: pending – initial state (still waiting), completed – Promise successful, Rejected – Promise failed. A promise is said to be resolved if it is fulfilled or rejected but is not pending .

Promise combinators are used to handle Promises more easily. JavaScript has four Promise combinators, but they are at different stages of ECMAScript.

Promise.all()

Promise.all() is a method that accepts an iterable of Promise objects and returns a single Promise. If all promises are fulfilled, the returned promises are also fulfilled.

const P1 = Promise.resolve(18);
const P2 = new Promise((resolve, reject) => {
    
    
  setTimeout(() => {
    
    
    resolve(5);
  }, 100);
});
const P3 = Promise.resolve("18.5.");
const promises = [P1, P2, P3];

Promise.all(promises).then((values) => {
    
    
  console.log(values);
});
//Array [18, 5, "18.5."]

Alternatively, use async/await:

async function f() {
    
    
  const P1 = Promise.resolve(18);
  const P2 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve(5);
    }, 100);
  });
  const P3 = Promise.resolve("18.5.");
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.all(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Array [18, 5, "18.5."]

Even if the second Promise takes the longest to resolve, the order in the returned Promise will always remain the same as the order in its source Promise.

If you pass an empty object, then it returns a resolved Promise.

Promise.all() also accepts non-Promise values ​​and returns them unchanged.

async function f() {
    
    
  const promises = [1, 2, 3];
  try {
    
    
    const result = await Promise.all(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Array [1, 2, 3]

If at least one Promise is rejected, the returned Promise is rejected. This error becomes the result of the entire Promise.all() method. The results of other promises are completely ignored.

async function f() {
    
    
  const P1 = Promise.resolve(18);
  const P2 = Promise.resolve(5);
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      reject(new Error("Error happened!"));
    }, 200);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.all(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Error: Error happened!

Promise.all() has been part of JavaScript since Promise was introduced in ES2015, and a Promise static method has also been added: Promise.race()

Promise.race()

Promise.race() returns the first resolved Promise from the iterable Promise object received. Then the promise can be fulfilled.

async function f() {
    
    
  const P1 = Promise.resolve(18);
  const P2 = Promise.resolve(5);
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve("18.5.");
    }, 100);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.race(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //18

Or it could be a rejected Promise.

async function f() {
    
    
  const P1 = Promise.reject(new Error("Error happened!"));
  const P2 = Promise.resolve(5);
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve("18.5.");
    }, 100);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.race(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Error: Error happened!

If you pass an empty object, the returned Promise will hang forever.

If Promise.race() receives a non-Promise value, it resolves to the first value found in the iterable.

async function f() {
    
    
  const promises = [1, 2, 3];
  try {
    
    
    const result = await Promise.race(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //1

Promise.allSettled()

The Promise.allSettled() method was finally added in ES2020 . Older browsers may still require PuTTY to support it. This method waits for all received commitments to settle. It returns a Promise:

  • { status: “fulfilled”, value: result } indicates a successful response or
  • { status: “rejected”, Reason: error} for responses with errors.
async function f() {
    
    
  const P1 = Promise.reject(new Error("Error happened!"));
  const P2 = 5;
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve("18.5.");
    }, 100);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.allSettled(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Array [
//Object { status: "rejected", reason: Error: Error happened! },
//Object { status: "fulfilled", value: 5 },
//Object { status: "fulfilled", value: "18.5." }]

As we saw in the example above, methods can also receive non-promise values.

If an empty iterable is passed, Promise.allSettled() will return a resolved Promise object as an empty array.

async function f() {
    
    
  try {
    
    
    const result = await Promise.allSettled([]);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //Array []

Promise.any()

Promise.any() is the latest Promise combinator and is currently in stage 3 of the TC39 process . It takes an iterable object and returns that Promise once one of the Promises is satisfied.

async function f() {
    
    
  const P1 = Promise.resolve(18);
  const P2 = Promise.resolve(5);
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve("18.5.");
    }, 100);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.any(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //18

The difference between this method and Promise.all() is that Promise.all() returns an array of fulfillment values, while Promise.any() returns only the first fulfillment value. Promise.race() differs from Promise.any() in that Promise.race() returns the first fixed value (fulfilled or rejected), while Promise.any() ignores rejected Promises until the first Promise is fulfilled.

async function f() {
    
    
  const P1 = Promise.reject(new Error("Error happened!"));
  const P2 = Promise.resolve(5);
  const P3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve("18.5.");
    }, 100);
  });
  const promises = [P1, P2, P3];
  try {
    
    
    const result = await Promise.any(promises);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
}
f(); //5

If an empty iterable is passed, this method will return a resolved promise.

If all given Promises are rejected, this method asynchronously rejects AggregateError , a new Error subclass that groups individual errors together.

Promise.any() is still experimental and not yet fully supported by browsers.

おすすめ

転載: blog.csdn.net/Gas_station/article/details/131829241