Search code examples
javascriptcallbackarrow-functions

How does the function arguments are passed in the following promise code


I have the following code snippet. It is a promise, which is rejected after 2 seconds. And after two seconds it gives the output Error my custom error

const promise = new Promise((resolve, reject) => {
  setTimeout(() => reject('my custom error'), 2000);
});

function onSuccess() {
  console.log('Success');
}

function onError(err) {
  console.log('Error', err);
}

promise.then(onSuccess);
promise.catch(onError);
// promise.catch((err) => onError(err));

You can see I have added two promise.catch statements. And they both give the same output. My question is how is the err argument (my custom error) from the reject is being passed in the following catch statement promise.catch(onError).


Solution

  • catch method takes a callback function. when the promise is rejected that callback is called with the error.

    In your case then onError function is the callback. So when promise is rejected it takes that callback and calls it.

    A typical example can be something like

    catch(callback) {
      // some logic 
      callback(new Error('error message'));
    }
    

    So your onError function receives the argument as err object.

    Do check this medium article on how a promise can typically be implemented

    It will give you more idea on what is happening under the hood.

    Also note that

    in both cases

    function onError(err) {
      console.log('Error', err);
    }
    
    promise.catch(onError);
    promise.catch((err) => onError(err));
    

    you are passing a function to catch as callback. In the first case it an a normal function will be called with whatever argument catch called its callback with. So for instance had catch method passed 3 arguments to callback all three will be available to onError

    In the second case you are passing an inline arrow function. Now that acts as the callback which is called with all the arguments catch block passes but you are using only the first argument and forwarding it to onError function