gpt4 book ai didi

javascript - 将原型(prototype)方法传递给 Promise 的 then 方法

转载 作者:行者123 更新时间:2023-12-03 04:39:17 25 4
gpt4 key购买 nike

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

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

我收到以下错误:

TypeError: undefined is not a function

但是,当我执行该 block 时:

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

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

在我看来它们应该是相同的。我是否遗漏了一些明显的东西?

Node v6.10.1

最佳答案

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

您需要将 call 绑定(bind)到 Buffer.prototype.toString,如下所示 Buffer.prototype.toString.call.bind(Buffer.prototype.toString)

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

关于javascript - 将原型(prototype)方法传递给 Promise 的 then 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com