简体   繁体   中英

What is passed to the function in a Promise .catch block?

What's the general difference between these two styles of handling .catch blocks in Promises:

...
.catch(e => myMethod(e))
...
.catch(myMethod)

What does a Promise's .catch pass to the received method?

eg Can there be additional arguments?

In both cases, there is only one argument.

There's no fundamental difference between these two styles, except that an arrow function behaves differently than a real function , especially this will be undefined or window (depending on whether strict mode is enabled or not) with a function , and with an arrow function it's the same this as the context in which it is declared.


From this MDN Catch Syntax documentation :

This .catch has one argument: reason : The rejection reason.

From this MDN Arrow Function documentation :

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords . Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

In catch(e => myMethod(e)) , you are passing an anonymous function which takes a parameter e and calls myMethod(e)

In catch(myMethod) , you are directly passing your myMethod instead of that anonymous function (in above case), which takes a parameter e .

So, both are same. And the parameter passed e is the "reason" for being rejected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM