What is passed to the function in a Promise .catch

2020-05-06 13:07发布

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?

e.g. Can there be additional arguments?

2条回答
趁早两清
2楼-- · 2020-05-06 14:01

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.

查看更多
Juvenile、少年°
3楼-- · 2020-05-06 14:08

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.

查看更多
登录 后发表回答