异步等待众多之一

时间:2019-01-15 00:49:01

标签: javascript node.js async-await

有没有一种方法可以对一组promise执行异步等待,但是只等待第一个完成?

例如:

async function run() {
    const ms = Math.floor(Math.random() * 1000);
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function test() {
    await Promise.first([run(), run(), run(), run(), run()]); // first or similar?

    // this line would be reached after the first run() finished execution
    // receieve results from first completion
}

1 个答案:

答案 0 :(得分:4)

您可以使用Promise.race

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
});

var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race