Skip to content

Commit

Permalink
Promise.try() can take additional arguments (mdn#36434)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena authored Oct 22, 2024
1 parent bd48972 commit 3730011
Showing 1 changed file with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@ The **`Promise.try()`** static method takes a callback of any kind (returns or t

```js-nolint
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 no arguments. It can do anything—either return a value, throw an error, or return a promise.
- : 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 to `func`.

### Return value

Expand Down Expand Up @@ -58,6 +63,20 @@ The difference is that the callback passed to {{jsxref("Promise/then", "then()")

`Promise.try()`, combined with {{jsxref("Promise/catch", "catch()")}} and {{jsxref("Promise/finally", "finally()")}}, 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.

Like {{domxref("Window/setTimeout", "setTimeout()")}}, `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()
Expand Down

0 comments on commit 3730011

Please sign in to comment.