[英]Promises with ES6 destructuring?
我尝试将Promises
与ES6解构语法混合(仅出于实验目的),但是以下代码引发错误:
function delay(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), ms)
})
}
const { then } = delay(2000)
console.log(typeof then) // ==> 'function'
// throws TypeError:
then(() => {
console.log(`done!`)
})
在Node.js v7.10.1上打印:
TypeError:无法读取未定义的属性'Symbol(promise_state_symbol)'
Chrome控制台还会引发TypeError
,但消息不同:
Uncaught TypeError:方法Promise.prototype.then在不兼容的接收器上调用undefined
这些错误对我说的并不多。 有什么更好的解释呢?
这意味着, then
是方法,你没有把它在任何情况下-你说这就是因为没有任何一个功能this
方面 (或“接收器”,作为第二个错误消息,将其命名为正常)。 您基本上是
const then = Promise.prototype.then
console.log(typeof then) // ==> 'function'
then(() => {}) // throws TypeError
您可以使用call
const promise = delay(2000);
then.call(promise, console.log);
或者只是正确调用promise.then(console.log)
。
您正在将then
方法分配给变量, then
访问this
。 您可以使用bind
实现您想要的。
基本上,javascript中的方法只是使用this
函数。 如果您在“窃取”该功能并且不提供该值,那么您将处于危险境地。
另外, then
你提取是最有可能从Promise.prototype
,不特定的延时功能的函数。
您刚刚找到了从对象中获取方法的绝佳方法。 完全与解构无关...
let p;
const {then} = p = delay(2000);
const then1 = p.then;
console.assert(then === Promise.prototype.then)
console.assert(then1 === then, 'thens aren\'t the same')
但是你想then
,以某种方式确保,那你怎么称呼它右边的承诺。
所以你可以选择
const p = delay(2000);
const then = p.then.bind(p);
…
或构造另一个匿名函数
const p = delay(2000);
const then = fn => p.then(fn)
请注意,这不是您想要的,因为它在您调用then
时开始超时。
const then = fn => delay(2000).then(fn) // ⚠ setTimeout gets called when you are calling then.
我看不到您如何在一线达成目标,但是其他人可能有一个主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.