1

I was reading about async/await usage and best practices and someone suggested in the comments that this code:

const makeRequest = async () => { const value1 = await promise1() const value2 = await promise2() return promise3(value1, value2) } 

can be written like this:

const makeRequest = async () => { const value1 = promise1() const value2 = promise2() return promise3(await value1, await value2) } 

Are these the same? If not, then what is the difference?

2 Answers 2

2

They are different. The biggest difference is that the first example has to wait for promise1 to complete before even trying promise2.

In the first example, the flow looks like this:

  1. Call promise1

  2. Wait for promise1 to complete and store in value1

  3. Call promise2

  4. Wait for promise2 to complete and store in value2

In the second example, the flow looks like this:

  1. Call promise1

  2. Call promise2

  3. Wait for promise1 and promise2 to complete

In the second example, promise1 and promise2 can both be called so that promise2 doesn't have to wait for promise1 to complete.

Another way this might look is using Promise.all

ex:

const makeRequest = async () => { const [value1, value2] = await Promise.all([promise1(), promise2()]) return promise3(value1, value2) } 

Promise.all will kick off both promises and wait for them all to complete before returning: Promise.all docs

The promise values are then placed into an array in the order the promises were in the promise array. Using destructuring, we can get those values back from the values array inline.

Sign up to request clarification or add additional context in comments.

2 Comments

I would also link array destructing
Thanks @JBis, I added that.
1
const makeRequest = async () => { const value1 = await promise1() const value2 = await promise2() // waits for promise1() to complete before this statement is executed. wastes time if value2 does not depend on value1 return promise3(value1, value2) } 
const makeRequest = async () => { const value1 = promise1() //calls promise, does not wait for it to resolve const value2 = promise2() //calls the next promise, does not wait for it to resolve, return promise3(await value1, await value2) // calls promise 3 after both values have resolved } 

Clearly the second version is more optimal for promises that may run in parallel. It is similar to Promise.all where all promises are called parallelly

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.