Search code examples
javascriptfunctiones6-promisefirst-class-functions

Why i only need to provide "console.log" to my catch promise method to log error?


I have a simple promise, but I wonder why in my catch method I only need to pass "console.log" and it will automatically log that error if it happens? enter image description here

Does it have something to do with the fact that catch automatically gives us an error object or is it something else?


Solution

  • In your case, you would pass the function console.log to the catch method. console.log method just prints each parameter in the console. Inside the catch method, the passed function will be executed on a reject/error of the promise.

    Here is an example of passing functions:

    
    function a(method) {
        method("Hello World");
    }
    
    a(console.log);
    
    

    In this case, the console.log function is available as method in the a function as it has been passed as a parameter. This is the reason, the code prints Hello World in the console.