A
A
Alexander Buki2019-07-03 09:41:50
JavaScript
Alexander Buki, 2019-07-03 09:41:50

What is the difference in performing asynchronous operations?

Question in the test task:
What is the difference in performing asynchronous operations?
await fetchAPI1(id);
await fetchAPI2(id);
and
await Promise.all([fetchAPI1(id), fetchAPI2(id)])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-07-03
@alexbuki

1.
Start fetchAPI1,
wait for fetchAPI1 to complete,
start fetchAPI2,
wait for fetchAPI2 to complete
2.
Start fetchAPI1,
start fetchAPI2,
wait for fetchAPI1 to complete,
wait for fetchAPI2 to complete.
(If fetchAPI2 completed earlier, then request2's promise is in the fulfilled state and await will pass immediately, at the end of the current event loop)
3.
Start fetchAPI1,
start fetchAPI2,
wait for fetchAPI1 and fetchAPI1 to complete, return an array of fetchAPI1 and fetchAPI1 results.
The difference between 2 and 3 is quite small.
Only all this can be rewritten correctly as

const fetchData = id => {
  return Promise.all([fetchAPI1(id), fetchAPI2(id)])
    .then(([response1, response2]) => ({response1, response2}));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question