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:06

    As you see, the race() will return the promise instance which is firstly resolved or rejected:

    var p1 = new Promise(function(resolve, reject) { 
        setTimeout(resolve, 500, 'one'); 
    });
    var p2 = new Promise(function(resolve, reject) { 
        setTimeout(resolve, 100, 'two'); 
    });
    
    Promise.race([p1, p2]).then(function(value) {
      console.log(value); // "two"
      // Both resolve, but p2 is faster
    });

    For a scenes to be used, maybe you want to limit the cost time of a request :

    var p = Promise.race([
        fetch('/resource-that-may-take-a-while'),
        new Promise(function (resolve, reject) {
             setTimeout(() => reject(new Error('request timeout')), 5000)
        })
    ])
    p.then(response => console.log(response))
    p.catch(error => console.log(error))
    

    With the race() you just need to get the returned promise, you needn't care about which one of the promises in the race([]) firstly returned,

    However, without the race, just like your example, you need to care about which one will firstly returned, and called the callback in the both success callback.

提交回复
热议问题