Don’t wait in the loop, 6 best practices for asynchronous operations!

Beck Moulton
3 min readAug 14, 2024

Two days ago, a colleague was asked a question during an interview: “What should we do if we request multiple different interfaces?” The colleague replied: “We can put these interfaces into an array and then loop the request through a forloop!"

Well… this is one way, but it’s not good. Plus, asynchronous issues have become a common problem in interviews, so today we will talk about the best practices of asynchronous requests to help you solve asynchronous programming and interview problems.

01: Do not use await for circular requests

We should not use awaitinside a loop. Instead we can use the promise.allmethod:

// ❌
async function fn(reqs) {
const results = [];
for (const req of reqs) {
//
results.push(await req);
}
return results;
}// ✅
async function fn(reqs) {
// Promise
const promises = reqs.map((req) => req);
// ,
const results = await Promise.all(promises);
return results
}

02: Do not perform return operations in promises

Do not return values in the Promise constructor function. The values returned from there are useless. They also do not affect the state of the Promise.

  • The correct way is to use resolveto pass values.
  • If there is an error, use rejectto pass the error.
// ❌
new Promise((resolve

--

--

Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton