Skip to content
jshacks.dev
Async

Promise.try: Starting a Chain From Sync or Async Code

Learn how Promise.try runs a function that may be sync or async and always returns a promise, turning thrown errors into rejections on Node.js 24.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ, Apache Kafka and Node.js logos.

You have a function that might be synchronous and might return a promise, and you want to handle both the same way: a promise out, and any thrown error turned into a rejection. Before Promise.try the options were awkward. new Promise((resolve) => resolve(fn())) works but reads like noise, and Promise.resolve().then(fn) delays the call by a microtask. Promise.try(fn) calls the function immediately and synchronously, and wraps whatever happens in a promise. It is part of ES2025, and it is available in Node.js 24, so this post uses that version. It covers the exact behavior with printed output, the bug it fixes (sync throws escaping a promise API), argument passing and when an async function already does the same job.

The problem it solves

An API that is supposed to return a promise sometimes throws synchronously instead, and callers who wrote .catch() never get a chance to handle it.

JavaScript
function loadUser(id) {
  if (typeof id !== "number") {
    throw new TypeError("id must be a number");
  }
  return Promise.resolve({ id });
}

try {
  loadUser("abc").catch((error) => console.log("caught by catch:", error.message));
} catch (error) {
  console.log("caught by try:", error.message);
}
Text
caught by try: id must be a number

The .catch() was never reached, because loadUser threw before it returned a promise. A caller who relied on promise error handling has to remember to add a try/catch as well, which is the kind of inconsistency that causes production crashes. The function should always return a promise or always throw, never one or the other.

The solution

Promise.try calls the function right away. A return value becomes a fulfilled promise, a returned promise is followed and a throw becomes a rejection.

JavaScript
function loadUser(id) {
  return Promise.try(() => {
    if (typeof id !== "number") {
      throw new TypeError("id must be a number");
    }
    return { id };
  });
}

loadUser("abc").catch((error) => console.log("caught by catch:", error.message));
loadUser(7).then((user) => console.log("loaded", user));
Text
caught by catch: id must be a number
loaded { id: 7 }

Now both outcomes arrive as promises, and a caller needs only one error path. In an async function, this behavior is built in, since a throw becomes a rejection automatically. Promise.try is for functions that are not async, or for wrapping a function you did not write.

It runs synchronously

This is the difference from Promise.resolve().then(fn). With Promise.try, the function runs before the next line, so side effects keep their order.

JavaScript
console.log("before");

Promise.try(() => console.log("inside try"));
Promise.resolve().then(() => console.log("inside then"));

console.log("after");
Text
before
inside try
after
inside then

The Promise.try callback ran immediately, between before and after. The then callback waited for the microtask queue. If the function does something that must happen now, such as reading a value that may change, the difference matters.

Handling sync and async results alike

JavaScript
const syncFn = () => "sync value";
const asyncFn = async () => "async value";
const throwingFn = () => {
  throw new Error("sync throw");
};
const rejectingFn = async () => {
  throw new Error("async rejection");
};

for (const fn of [syncFn, asyncFn, throwingFn, rejectingFn]) {
  await Promise.try(fn).then(
    (value) => console.log("fulfilled:", value),
    (error) => console.log("rejected:", error.message),
  );
}
Text
fulfilled: sync value
fulfilled: async value
rejected: sync throw
rejected: async rejection

All four reach the same two handlers, whether they threw immediately, rejected later, returned a value or returned a promise. That uniformity is the entire value of the method.

Passing arguments

Extra arguments after the function are passed to it, which avoids a wrapper closure.

JavaScript
function add(a, b) {
  return a + b;
}

console.log(await Promise.try(add, 2, 3));

const parse = (text) => JSON.parse(text);

try {
  await Promise.try(parse, "{broken");
} catch (error) {
  console.log(error.name);
}
Text
5
SyntaxError

Promise.try(add, 2, 3) is the same as Promise.try(() => add(2, 3)).

Use: a safe entry point for user callbacks

A library that accepts a callback from users cannot know whether it is sync, async or buggy. Wrapping it gives one error path.

JavaScript
function runHook(hook, context) {
  return Promise.try(hook, context).catch((error) => {
    console.log("hook failed:", error.message);
    return null;
  });
}

await runHook((ctx) => ctx.name.toUpperCase(), { name: "ada" }).then(console.log);
await runHook(async (ctx) => ctx.missing.toUpperCase(), {}).then(console.log);
await runHook(() => {
  throw new Error("bad hook");
}).then(console.log);
Text
ADA
hook failed: Cannot read properties of undefined (reading 'toUpperCase')
null
hook failed: bad hook
null

A hook that was a plain function, an async function and a function that throws, all resulted in the same recovery path. Without the wrapper, the third would have thrown out of runHook.

Use: a chain starting point

Starting a chain with a function that might throw, without an intermediate Promise.resolve().

JavaScript
const result = await Promise.try(() => JSON.parse('{"count": 2}'))
  .then((data) => data.count * 10)
  .catch(() => 0);

console.log(result);

const fallback = await Promise.try(() => JSON.parse("nope"))
  .then((data) => data.count * 10)
  .catch(() => 0);

console.log(fallback);
Text
20
0

When an async function does the same

JavaScript
async function loadUser(id) {
  if (typeof id !== "number") throw new TypeError("id must be a number");
  return { id };
}

await loadUser("abc").catch((error) => console.log(error.message));
Text
id must be a number

If you control the function, declaring it async is the simplest fix. Promise.try is for the other case: wrapping a function that comes from elsewhere, or a function that must stay synchronous for other callers. Do not mark a function async purely to get this behavior if other code relies on it returning a value immediately.

Support and fallbacks

Promise.try shipped in Node.js 24 and in current browsers. For older runtimes, the equivalent is a short function.

JavaScript
const promiseTry = (fn, ...args) =>
  new Promise((resolve) => resolve(fn(...args)));

The new Promise executor runs synchronously and converts a throw into a rejection, which gives the same semantics. TypeScript needs lib set to ES2025 or later for the built-in type.

What it does not do

It does not make a blocking function non-blocking. If fn runs a slow loop, Promise.try waits for it just as a plain call would. It also does not catch asynchronous errors from callbacks that fire later: only a throw during the call, a rejection of the returned promise and nothing else.

Adopting it in an existing codebase

The easiest place to start is at the boundaries where your code calls functions it does not control: plugin hooks, user supplied callbacks, event handlers that return promises, configuration functions. Those are the places where a throw from foreign code can escape into your own control flow and skip your cleanup. Wrapping the call in Promise.try and attaching a single catch gives you one place to log and recover, and the rest of the surrounding code stays straight-line.

Be careful not to wrap everything by reflex. Code you control, particularly async functions, already converts throws into rejections, so wrapping it again only adds noise. The wrapper earns its place when the type of the callee is unknown or mixed, and when synchronous execution order matters. If you are supporting runtimes without the method, add the three-line helper once in a utilities module and import it, so the day you drop old runtimes you replace one definition and change nothing else.

One last note on style. Because the callback runs synchronously, any side effects it has happen before Promise.try returns. If you need the work deferred, for example so a caller can attach handlers first, use queueMicrotask or Promise.resolve().then, and not Promise.try.

Testing code that uses Promise.try

A wrapper built on Promise.try should be tested with four kinds of callback: one that returns a value, one that returns a promise, one that throws synchronously and one that returns a rejected promise. Assert that all four come out as promises, and that the last two reach the same catch. Add a test for ordering, to prove that the callback runs synchronously and not in a microtask, by pushing a marker into an array inside the callback and another one right after the call, and checking their order. Test that extra arguments are forwarded. If your code supports runtimes without the method, run the same test file against the polyfill by deleting Promise.try first, and assert that the behavior is identical. A polyfill that differs in ordering is the kind of defect that appears only in older environments.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 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.