Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q756】Promise.race 与 Promise.any #812

Open
shfshanyue opened this issue Apr 6, 2024 · 1 comment
Open

【Q756】Promise.race 与 Promise.any #812

shfshanyue opened this issue Apr 6, 2024 · 1 comment
Labels

Comments

@shfshanyue
Copy link
Owner

简介二者区别,以及使用场景

@shfshanyue shfshanyue added the js label Apr 6, 2024
@GrammyLi
Copy link

GrammyLi commented Dec 4, 2024

Promise.race:返回 第一个完成(无论是成功还是失败) 的 Promise 结果。

Promise.any:返回 第一个成功 的 Promise 结果,如果没有任何 Promise 成功,返回 AggregateError。

function PromiseRace(promiseArr) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promiseArr)) {
      return reject(new Error("Input must be an array"));
    }

    for (let i = 0; i < promiseArr.length; i++) {
      Promise.resolve(promiseArr[i]).then(resolve).catch(reject);
    }
  });
}

const p1 = new Promise((res, rej) => setTimeout(res, 1000, "p1"));
const p2 = new Promise((res, rej) => setTimeout(res, 500, "p2"));
const p3 = new Promise((res, rej) => setTimeout(res, 1500, "p3"));

PromiseRace([p1, p2, p3]).then(console.log).catch(console.error);
function PromiseAny(promiseArr) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promiseArr)) {
      return reject(new Error("Input must be an array"));
    }

    let errors = [];
    let count = 0;

    for (let i = 0; i < promiseArr.length; i++) {
      Promise.resolve(promiseArr[i])
        .then(resolve)
        .catch((error) => {
          errors.push(error);
          count++;
          if (count === promiseArr.length) {
            reject(new AggregateError(errors, 'All promises failed'));
          }
        });
    }
  });
}

const p1 = new Promise((res, rej) => setTimeout(rej, 1000, "p1 error"));
const p2 = new Promise((res, rej) => setTimeout(res, 500, "p2"));
const p3 = new Promise((res, rej) => setTimeout(rej, 1500, "p3 error"));

PromiseAny([p1, p2, p3]).then(console.log).catch(console.error);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants