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

空扰寡人 提交于 2019-12-04 05:49:57

问题


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 receiving method?

e.g. Can there be additional arguments?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/58167143/what-is-passed-the-the-function-in-a-promise-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!