Search code examples
javascriptes6-promise

What is the difference between Promise((resolve,reject)=>{}) and Promise(resolve =>{})?


As we know that Promise constructor takes one executor function which has two parameters which we use to generate success case or failure case. Today I was programming and I was stuck but later I solve the issue but I found one thing that needs to be understood.

What is the difference between

new Promise(resolve => {

    // resolve

});

and

new Promise((resolve,reject)=>{

    // resolve
    // reject

});

Can we do like this?

new Promise(resolve => {

    // resolve

}, reject => {

    // reject

});

Examples will be more appreciated. Thanks !!!


Solution

  • 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).