Member-only story
Don’t wait in the loop, 6 best practices for asynchronous operations!
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 for
loop!"
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 await
inside a loop. Instead we can use the promise.all
method:
// ❌
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
resolve
to pass values. - If there is an error, use
reject
to pass the error.
// ❌
new Promise((resolve…