Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Promise.try()

Baseline2025
Newly available

ThePromise.try() static method takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in aPromise.

Syntax

js
Promise.try(func)Promise.try(func, arg1)Promise.try(func, arg1, arg2)Promise.try(func, arg1, arg2, /* …, */ argN)

Parameters

func

A function that is called synchronously with the arguments provided (arg1,arg2, …,argN). It can do anything—either return a value, throw an error, or return a promise.

arg1,arg2, …,argN

Arguments to pass tofunc.

Return value

APromise that is:

  • Already fulfilled, iffunc synchronously returns a value.
  • Already rejected, iffunc synchronously throws an error.
  • Asynchronously fulfilled or rejected, iffunc returns a promise.

Description

You may have an API that takes a callback. The callback may be synchronous or asynchronous. You want to handle everything uniformly by wrapping the result in a promise. The most straightforward way might bePromise.resolve(func()). The problem is that iffunc() synchronously throws an error, this error would not be caught and turned into a rejected promise.

The common approach (lifting a function call result into a promise, fulfilled or rejected) often looks like this:

js
new Promise((resolve) => resolve(func()));

ButPromise.try() is more helpful here:

js
Promise.try(func);

For the built-inPromise() constructor, errors thrown from the executor are automatically caught and turned into rejections, so these two approaches are mostly equivalent, except thatPromise.try() is more concise and readable.

Note thatPromise.try() isnot equivalent to this, despite being highly similar:

js
Promise.resolve().then(func);

The difference is that the callback passed tothen() is always called asynchronously, while the executor of thePromise() constructor is called synchronously.Promise.try also calls the function synchronously, and resolves the promise immediately if possible.

Promise.try(), combined withcatch() andfinally(), can be used to handle both synchronous and asynchronous errors in a single chain, and make promise error handling appear almost like synchronous error handling.

LikesetTimeout(),Promise.try() accepts extra arguments that are passed to the callback. This means instead of doing this:

js
Promise.try(() => func(arg1, arg2));

You can do this:

js
Promise.try(func, arg1, arg2);

Which are equivalent, but the latter avoids creating an extra closure and is more efficient.

Examples

Using Promise.try()

The following example takes a callback, "lifts" it into a promise, handles the result, and does some error handling:

js
function doSomething(action) {  return Promise.try(action)    .then((result) => console.log(result))    .catch((error) => console.error(error))    .finally(() => console.log("Done"));}doSomething(() => "Sync result");doSomething(() => {  throw new Error("Sync error");});doSomething(async () => "Async result");doSomething(async () => {  throw new Error("Async error");});

In async/await, the same code would look like this:

js
async function doSomething(action) {  try {    const result = await action();    console.log(result);  } catch (error) {    console.error(error);  } finally {    console.log("Done");  }}

Calling try() on a non-Promise constructor

Promise.try() is a generic method. It can be called on any constructor that implements the same signature as thePromise() constructor.

The following is a slightly more faithful approximation of the actualPromise.try() (although it should still not be used as a polyfill):

js
Promise.try = function (func) {  return new this((resolve, reject) => {    try {      resolve(func());    } catch (error) {      reject(error);    }  });};

Because of howPromise.try() is implemented (i.e., thetry...catch), we can safely invokePromise.try() with itsthis set to any custom constructor, and it will never synchronously throw an error.

js
class NotPromise {  constructor(executor) {    // The "resolve" and "reject" functions behave nothing like the native    // promise's, but Promise.try() just calls resolve    executor(      (value) => console.log("Resolved", value),      (reason) => console.log("Rejected", reason),    );  }}const p = Promise.try.call(NotPromise, () => "hello");// Logs: Resolved helloconst p2 = Promise.try.call(NotPromise, () => {  throw new Error("oops");});// Logs: Rejected Error: oops

UnlikePromise(), thisNotPromise() constructordoes not gracefully handle exceptions while running the executor. But despite thethrow,Promise.try() still catches the exception, passing it toreject() to log out.

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-promise.try

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp