javascript - 为什么我不能将 Javascript Promise 存储在变量中,然后调用 "then"和 "catch"方法?

标签 javascript asynchronous ecmascript-6 promise

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/

相关文章:

javascript - React - 在 map 函数中表达预期

javascript - 主干模型两次触发 "change"事件

javascript - OAuth.io 连接失败

javascript - 无法进入异步(同步)函数/空结果的回调

node.js - 迭代如何等待 Node.js 中的 sqlite3 查询?

node.js - Nodejs解构require

javascript - 无法访问函数内的 Polymer 属性

Linux 非阻塞套接字

javascript通过映射根据另一个对象更新对象键/值

javascript - 当我需要同时过滤多个内容时,如何调用一次过滤器?