Bla*_*mba 6 javascript node.js promise es6-promise
'use strict';
Promise.resolve(() => 'John')
.then((args) => {
console.log(args);
throw new Error('ops')
})
.catch((ex) => {
console.log(ex)
})
.then(() => {
throw new Error('ups')
console.log('Doe')
})
Run Code Online (Sandbox Code Playgroud)
我认为console.log(args);应该输出'John',但是当我运行此代码时,输出是[ [Function] ]
所以我很困惑.
Promise.resolve将创建一个新的 Promise,并使用您传递给它的值进行解析。因此,在您的情况下,您的承诺实际上是通过函数对象解决的。这意味着,then处理程序被传递给函数对象本身。
你应该做的是
new Promise((resolve, reject) => resolve('John'))
.then(args => {
console.log(args);
throw new Error('ops')
})
.catch(console.log.bind(console));
Run Code Online (Sandbox Code Playgroud)
现在,您正在创建一个Promise对象,并使用 value 解析该对象John。
如果您希望您的 Promise 能够轻松地用一个值来解析,那么不要传递函数对象,而是将实际值本身传递给Promise.resolve函数。
Promise.resolve('John')
.then(args => {
console.log(args);
throw new Error('ops')
})
.catch(console.log.bind(console));
Run Code Online (Sandbox Code Playgroud)
现在,您有一个 Promise,已用 value 解析John,并且then处理程序将获得解析后的 value John。
注意:当您知道轻松解析的实际方法时,这是创建 Promise 的推荐方法,这样您就可以避免Promise 构造函数反模式。
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |