Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Promise.all and for-await-of

Under the assumption that all the promises resolve, is asynchronous iteration (for-await-of loop) faster than using Promise.all?

From the specification on asynchronous iteration:

Each time we access the next value in the sequence, we implicitly await the promise returned from the iterator method.

Using asynchronous iteration:

let pages = [fetch('/echo/json/'), fetch('/echo/html/'), fetch('/echo/xml/')]
for await (let page of pages) {
    console.log(page)
}

Using Promise.all:

let pages = await Promise.all([fetch('/echo/json/'), fetch('/echo/html/'), fetch('/echo/xml/')])

pages.forEach(page => console.log(page))

Both of them fetch the pages in parallel but I'm wondering if asynchronous iteration starts looping before all the pages are finished fetching. I have tried throttling the network in my browser's devtools to simulate this but any differences were still too little to be noticed.

like image 338
rink.attendant.6 Avatar asked Aug 19 '18 10:08

rink.attendant.6


1 Answers

Is asynchronous iteration (for-await-of loop) faster than using Promise.all?

No. Both the loop and Promise.all will finish when the last promise resolves, which will be roughly at the same time. If the last promise that resolves is the first promise in the array, then Promise.all finishes immeadiately while the loop still has to iterate the other elements which might cause a small overhead but that should not matter. The only situation were it really matters is:

If one of the promises gets rejected, Promise.all exits immeadiately, while the loop has to reach that promise.

I'm wondering if asynchronous iteration starts looping before all the pages are finished fetching.

Yes you could get the first results a bit earlier, but all results will be available at the same time. Using the for loop would make sense if you want to show the data to the user, as he can start reading while the rest is still fetching, if you however want to accumulate the data it makes sense to await them all as it simplifies the iteration logic.

like image 77
Jonas Wilms Avatar answered Oct 24 '22 09:10

Jonas Wilms