How do you properly return multiple values from a promise?

后端 未结 9 1388
慢半拍i
慢半拍i 2020-12-04 14:14

I\'ve recently run into a certain situation a couple of times, which I didn\'t know how to solve properly. Assume the following code:

somethingAsync()
  .the         


        
9条回答
  •  無奈伤痛
    2020-12-04 14:53

    Whatever you return from a promise will be wrapped into a promise to be unwrapped at the next .then() stage.

    It becomes interesting when you need to return one or more promise(s) alongside one or more synchronous value(s) such as;

    Promise.resolve([Promise.resolve(1), Promise.resolve(2), 3, 4])
           .then(([p1,p2,n1,n2]) => /* p1 and p2 are still promises */);
    

    In these cases it would be essential to use Promise.all() to get p1 and p2 promises unwrapped at the next .then() stage such as

    Promise.resolve(Promise.all([Promise.resolve(1), Promise.resolve(2), 3, 4]))
           .then(([p1,p2,n1,n2]) => /* p1 is 1, p2 is 2, n1 is 3 and n2 is 4 */);
    

提交回复
热议问题