【问题标题】:Passing a prototype method to a Promise's then method [duplicate]将原型方法传递给 Promise 的 then 方法 [重复]
【发布时间】:2017-08-26 06:32:33
【问题描述】:

我有一个叫做 readFilePromise 的 promisified 方法,它从 fs 的 readFile 方法解析为一个 Buffer 对象。当我执行以下行时

return readFilePromise(filePath).then(Buffer.prototype.toString.call);

我收到以下错误:

TypeError: undefined is not a function

但是,当我执行块时:

return readFilePromise(filePath).then((data) => {
    return Buffer.prototype.toString.call(data);
});

我没有收到任何错误,代码执行良好。

在我看来,它们应该是相同的。我错过了什么明显的东西吗?

节点 v6.10.1

【问题讨论】:

  • 你真的要使用call而不是data.toString()吗?
  • 不,我想使用第一个示例。第二个仅用于演示目的。

标签: javascript node.js


【解决方案1】:

Buffer.prototype.toString.call 只是Function.prototype.call,它使用第一个对象作为上下文调用this。在您的第一个示例中,this 内的 call 调用将是 undefined

您需要像这样Buffer.prototype.toString.call.bind(Buffer.prototype.toString)call 绑定到Buffer.prototype.toString

return readFilePromise(filePath)
   .then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2017-02-07
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多