Understanding promise.race() usage

后端 未结 6 1510
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 17:14

As far as I know, there are two options about promise:

  • promise.all()

  • promise.race()

Ok, I know what promise.all()<

6条回答
  •  余生分开走
    2020-12-09 18:07

    Summary:

    Promise.race is a JS built in function that accepts an iterable of Promises (e.g. Array) as an argument. This function then asynchronously returns a Promise as soon as one in of the Promises passed in the iterable is either resolved or rejected.

    Example 1:

    var promise1 = new Promise((resolve, reject) => {
        setTimeout(() => resolve('Promise-one'), 500);
    });
    
    var promise2 = new Promise((resolve, reject) => {
        setTimeout(() => resolve('Promise-two'), 100);
    });
    
    Promise.race([promise1, promise2]).then((value) => {
      console.log(value);
      // Both resolve, but promise2 is faster than promise 1
    });

    In this example first an array of Promises is passed in Promise.race. Both of the promises resolve but promise1 resolves faster. Therefore the promise is resolved with the value of promise1, which is the string 'Promise-one'.

    Example 2:

    const promise1 = new Promise((resolve, reject) => {
        setTimeout(() => resolve('succes'), 2000);
    });
    
    const promise2 = new Promise((resolve, reject) => {
        setTimeout(() => reject('err'), 1000);
    });
    
    Promise.race([promise1, promise2])
      .then((value) => {
      console.log(value);
    }).catch((value) => {
      console.log('error: ' + value);
    });

    In this second example the second promise rejects faster than the first promise can resolve. Therefore Promise.race will return a rejected promise with the value of 'err' which was the value that Promise2 rejected with.

    The key point to understand is that Promice.race takes an iterable of Promises and returns a Promise based on the first resolved or rejected promise in that iterable (with the corresponding resolve() or reject() values).

提交回复
热议问题