Several recommended practices for writing good asynchronous JavaScript code

aifou
5 min readApr 11, 2024

no-async-promise-executor

It is not recommended to pass an `async` function to the `new Promise` constructor.

// ❌
new Promise(async (resolve, reject) => {});

// ✅
new Promise((resolve, reject) => {});

First, by using `async` in the `Promise` constructor, wrapping a `Promise` may be unnecessary. Additionally, if the `async` function throws an exception, the newly constructed `promise` instance will not `reject`, so the error cannot be caught.

no-await-in-loop

It is not recommended to use `await` inside a loop, as this usually indicates that the program is not fully leveraging the event-driven nature of `JavaScript`.

// ❌
for (const url of urls) {
const response = await fetch(url);
}

It is recommended to refactor these asynchronous tasks to run concurrently, which can significantly improve the execution efficiency of the code.

// ✅
const responses = [];
for (const url of urls) {
const response = fetch(url);
responses.push(response);
}

await Promise.all(responses);

no-promise-executor-return

It is not recommended to return a value from the `Promise` constructor function, as the…

--

--

aifou
aifou

Responses (2)