Skip to content
jshacks.dev
Async

Do not wrap async functions in new Promise

Do not wrap async functions in new Promise in JavaScript: an async executor loses its errors and the promise stays pending. Node.js 24.

1 min read
Summarize in AI

An async function already returns a promise. Passing one to new Promise as the executor hides its errors, and the outer promise never settles.

JavaScript
const delay = (ms, v) => new Promise((r) => setTimeout(r, ms, v));

process.on('uncaughtException', (err, origin) => {
  console.log('process saw', err.message, origin);
});

const bad = () =>
  new Promise(async (resolve) => {
    await delay(5);
    throw new Error('lost');
  });

const good = async () => {
  await delay(5);
  throw new Error('kept');
};

console.log(await Promise.race([bad(), delay(50, 'bad is still pending')]));
console.log(await good().catch((err) => err.message));
Text
process saw lost unhandledRejection
bad is still pending
kept

The constructor only catches errors thrown synchronously from the executor. An async executor returns its own promise, and when it throws after an await, that inner promise rejects with nobody listening. The outer promise is never resolved or rejected, so callers wait forever, and Node.js reports an unhandled rejection. The good version is the function itself, and its error reaches the caller.

ESLint has a rule for this, no-async-promise-executor. If you need resolve from an event, call it from a callback, not from an async executor.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.