This is not specific to Promises, just to callback functions.
new Promise((resolve) => {});
1 creates a Promise whose callback only takes the resolve
parameter. It’s not possible to call the reject function that would otherwise be provided.2
new Promise((resolve, reject) => {});
creates a Promise whose callback takes both parameters, including the one for rejecting.
The above two examples demonstrate how positional parameters work. The first parameter in the callback function is always the resolve function, the second one is always the reject function.
new Promise((reject, resolve) => {});
will create a Promise in which you can resolve with reject
and reject with resolve
.
You could throw
in the scope of the callback function or resolve(Promise.reject())
to cause a rejection to happen:
new Promise((resolve) => {
throw new Error("42");
// or `resolve(Promise.reject(new Error("42")));`
})
.catch(console.warn); // Prints warning “Error: "42"” in the console.
You cannot use new Promise((resolve) => {}, (reject) => {});
, since the Promise
constructor only takes one argument. The second callback function will just be ignored.
1: (resolve) => {}
is, of course, equivalent to resolve => {}
. But arrow function parameters actually always require parentheses. Simple and single parameters are the sole exception where they can be omitted. See the MDN article about arrow function syntax.
2: Using a regular function, new Promise(function(resolve){});
or new Promise(function(){});
you could access any argument with arguments[0]
(resolve) or arguments[1]
(reject).