I have understood that Promise is a special object in which javascript which helps us to deal with asynchronous tasks and catch errors which arise from it .
我熟悉以下用法:
func_returning_promise( )
.then((param)=>{do stuff with the param ; }
.catch((error) =>{console.log(error); }
我怎么不喜欢像这样使用 .then 和 .catch,所以我将 Promise 存储在变量 var myprom = func_returning_promise()
中。
但是当我像这样调用“then”和“catch”方法时,错误根本没有得到处理,也没有执行 catch
处理程序。
var myprom = func_returning_promise();
myprom.then((param)=> do stuff with param ) ;
myprom.catch((error)=> console.log(error)) ;
为什么我仍然出错,为什么 catch 处理程序没有执行?
它与 then
方法末尾的 semicolon ;
有什么关系吗?
This is not a duplicate of question Placement of catch before or after then
My question isn't about the placement of then and catch at all which the mentioned question addresses.
最佳答案
您的第一个和第二个代码片段不相同。
在第一个中,.catch()
将处理 func_returning_promise()
中抛出的任何错误或在.then()
处理程序。
在第二个中,.catch()
与原来的 promise 链接在一起,所以它只会捕获 func_returning_promise()
中抛出的错误.
要在没有链接的情况下实现与第一个示例等效的效果,您必须分配 .then
的结果到一个变量并调用 catch
关于:
var myprom = func_returning_promise();
var mysecondprom = myprom.then((param)=> do stuff with param ) ;
mysecondprom.catch((error)=> console.log(error)) ;
Promises 被设计成链式的。那么为什么不将它们链接起来呢?
关于javascript - 为什么我不能将 Javascript Promise 存储在变量中,然后调用 "then"和 "catch"方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967626/