Member-only story

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 returned value is unusable and does not affect the state of the `Promise`.

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

The normal practice is to pass the return value to `resolve`, and if an error occurs, pass it to `reject`.

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

require-atomic-updates

It is not recommended to combine assignment operations and **await** usage, as this may lead to race conditions.

Look at the code below, what do you think the final value of **totalPosts** will be?

// ❌
let totalPosts = 0;

async function getPosts(userId) {
const users = [{ id: 1, posts: 5 }, { id: 2, posts: 3 }];
await sleep(Math.random() * 1000);
return users.find((user) => user.id === userId).posts;
}

async function addPosts(userId) {
totalPosts += await getPosts(userId);
}

await

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

aifou
aifou

Responses (2)

Write a response

= It is recommended to refactor these asynchronous tasks to run concurrently =
If async request is to the site api, then sending 1000 requests simultaneously will result in 503 Too many requests or other deny.