for await of VS Promise.all

前端 未结 3 2345
情深已故
情深已故 2020-12-11 01:50

Is there any difference between this:

const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (c         


        
3条回答
  •  青春惊慌失措
    2020-12-11 02:44

    Yes, they absolutely are different. for await is supposed to be used with asynchronous iterators, not with arrays of pre-existing promises.

    Just to make clear,

    for await (const res of items.map(e => somethingAsync(e))) …
    

    works the same as

    const promises = items.map(e => somethingAsync(e));
    for await (const res of promises) …
    

    or

    const promises = [somethingAsync(items[0]), somethingAsync(items[1]), …);
    for await (const res of promises) …
    

    The somethingAsync calls are happening immediately, all at once, before anything is awaited. Then, they are awaited one after another, which is definitely a problem if any one of them gets rejected: it will cause an unhandled promise rejection error. Using Promise.all is the only viable choice to deal with the array of promises:

    for (const res of await Promise.all(promises)) …
    

    See Waiting for more than one concurrent await operation and Any difference between await Promise.all() and multiple await? for details.

提交回复
热议问题