How can I run dependent asynchronous steps in the right order?
Quick answer
Use await on each asynchronous operation whose result the next step needs, then pass that result along. For example, await loading an order, use its customer ID to load the customer, and then create a receipt from both. If two operations do not depend on each other, start them together with Promise.all() instead of waiting for one before starting the other. [S1]
The question, the details, the next step.
A practical checklist
List each asynchronous operation and the values it requires.
Identify which earlier operation produces each required value.
Use
awaitbefore a dependent step, and pass the result into that step.Use
Promise.all()for operations that are independent but whose results are both needed later. [S1]Check that each step’s result is used only after that operation has been awaited.
A few more useful answers
Does `await` make every asynchronous operation sequential?
In a sequence where each operation is awaited before the next begins, it makes that code wait at each step. For independent operations, starting them together with Promise.all() can avoid unnecessary serial waiting. [S1]
Can I use `Promise.all()` when the second operation needs the first result?
Not as written if the second operation needs a value that does not exist until the first finishes. Await the first operation, pass its result to the second, and only group operations that are independent.
Does this sequence handle failures or retries?
No. The examples explain ordering and passing results, not how failures or retries should be handled. Those behaviors depend on the operations and the requirements of your application.
Sources
References used for this guide.
- [S1] Using promises — JavaScript | MDN developer.mozilla.org · Checked
