Javascript 将原型方法传递给Promise';s then方法
我有一个被推荐的方法叫做readFilePromise,它从fs的readFile方法解析为一个缓冲区对象。当我执行以下行时Javascript 将原型方法传递给Promise';s then方法,javascript,node.js,Javascript,Node.js,我有一个被推荐的方法叫做readFilePromise,它从fs的readFile方法解析为一个缓冲区对象。当我执行以下行时 return readFilePromise(filePath).then(Buffer.prototype.toString.call); 我得到以下错误: TypeError:undefined不是函数 但是,当我执行块时: return readFilePromise(filePath).then((data) => { return Buffer.
return readFilePromise(filePath).then(Buffer.prototype.toString.call);
我得到以下错误:
TypeError:undefined不是函数
但是,当我执行块时:
return readFilePromise(filePath).then((data) => {
return Buffer.prototype.toString.call(data);
});
我没有得到错误,代码执行良好
在我看来,它们应该是一样的。我错过了什么明显的东西吗
节点v6.10.1
Buffer.prototype.toString.call
只是函数.prototype.call
,它使用第一个对象作为上下文调用此
。在第一个示例中,这个内部调用
调用将是未定义的
您需要像这样将call
绑定到Buffer.prototype.toString
Buffer.prototype.toString.call.bind(Buffer.prototype.toString)
您真的想使用调用
而不是执行data.toString()
?不,我想使用第一个示例。第二次仅用于演示目的。
return readFilePromise(filePath)
.then(Buffer.prototype.toString.call.bind(Buffer.prototype.toString))