最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to implement Promise.race() with asyncawait - Stack Overflow

programmeradmin4浏览0评论

How can I implement Promise.race() method with async and await?

async function promiseRace(promises) {
  const results = [];
  for (const p of promises) {
    await p;
    results.push(p);
  }
  return results[0];
}

I've tried to implement it like above but this doesn't work.

How can I implement Promise.race() method with async and await?

async function promiseRace(promises) {
  const results = [];
  for (const p of promises) {
    await p;
    results.push(p);
  }
  return results[0];
}

I've tried to implement it like above but this doesn't work.

Share Improve this question asked Apr 14, 2019 at 18:22 Lukas CoorekLukas Coorek 2271 gold badge3 silver badges12 bronze badges 5
  • What specific problem you are facing? – Maheer Ali Commented Apr 14, 2019 at 18:23
  • Welcome to Stack Overflow. To improve this question show us what you have done. Show source code and describe what it is doing and what you need it to do. See How to ask a good question and How to create a Minimal, Complete, Verifiable example – Charlie Wallace Commented Apr 14, 2019 at 18:35
  • @CharlieWallace, I am not sure how that copy/paste comment applies to this question. The question shows what they have done, and there is source code. They tell us what it needs to do (Promise.race), and we can run their code and see it indeed does not work. So why did you post this comment? – trincot Commented Apr 14, 2019 at 18:45
  • @trincot, I am looking for more than "this doesn't work" in the question. The question can be improved by more explanation as to what the behavior is that does not work. – Charlie Wallace Commented Apr 14, 2019 at 18:49
  • The race part does not work. It always resolved/rejected with first parameter given to promiseRace function: promiseRace(fisrtPromise, secondPromise). Even if secondPromise resolved/rejected faster it still return firstPromise result. – Lukas Coorek Commented Apr 14, 2019 at 19:11
Add a comment  | 

6 Answers 6

Reset to default 8

You can't. When using await you halt execution onto one specific promise. To implement Promise.race manually, you have to fiddle with callbacks:

function race(promises) {
  return new Promise((resolve, reject) => {
     for(const promise of promises)
        promise.then(resolve, reject);
  });
}

You can't. Just like you cannot implement the Promise constructor using async/await. Remember that await is only syntactic sugar for then calls - and you cannot implement the basic promise combinators using only that.

You can by using a wrapper promise along with async await. In the wrapper promise, protect the resolve/reject so that only the first promise wins.

Promise.race example using async/await:

// Implements promise.race
const race = async (promises) => {
  // Create a promise that resolves as soon as
  // any of the promises passed in resolve or reject.
  const raceResultPromise = new Promise((resolve, reject) => {
    // Keep track of whether we've heard back from any promise yet.
    let resolved = false;

    // Protect the resolve call so that only the first
    // promise can resolve the race.
    const resolver = (promisedVal) => {
      if (resolved) {
        return;
      }
      resolved = true;

      resolve(promisedVal);
    };

    // Protect the rejects too because they can end the race.
    const rejector = (promisedErr) => {
      if (resolved) {
        return;
      }
      resolved = true;

      reject(promisedErr);
    };

    // Place the promises in the race, each can
    // call the resolver, but the resolver only
    // allows the first to win.
    promises.forEach(async (promise) => {
      try {
        const promisedVal = await promise;
        resolver(promisedVal);
      } catch (e) {
        rejector(e);
      }
    });
  });

  return raceResultPromise;
};

// *************
// Test Methods
// *************
const fetch = async (millis) => {
  await waitMillis(millis);
  return 'Async result: ' + millis + ' millis.';
};

const waitMillis = (millis) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, millis);
  });
};

const run = async () => {
  let result;

  result = await race([fetch(1), fetch(2), fetch(3)]);
  console.log('Winner', result);

  result = await race([fetch(3), fetch(2), fetch(1)]);
  console.log('Winner', result);

  result = await race([fetch(10), fetch(3), fetch(4)]);
  console.log('Winner', result);
};

run();

Why not:

const race = async (promiseArr) => {
    return Promise.race(promiseArr)
}

And inside your async function:

let dayAtTheRace = await race([
    my.promiseFunc(),
    my.wait(10)
])
function promiseRace(promises) {
  return new Promise((resolve, reject) => {
    promises.forEach(async (promise) => {
      try {
        const result = await promise;
        resolve(result);
      } catch (err) {
        reject(err);
      }
    });
  });

Here is my solution:

   async function promiseRace(promises) {
  const results = [];
  for (const p of promises) {
    results.push(await p);
  }
  return results[0];
}
发布评论

评论列表(0)

  1. 暂无评论