我重构了一个简单的实用程序来使用 promise 。它从网上获取 pdf 并将其保存到磁盘。一旦保存到磁盘,它应该在 pdf 查看器中打开文件。该文件出现在磁盘上并且有效,shell 命令打开 OSX 预览应用程序,但会弹出一个对话框,提示该文件为空。
一旦文件流写入磁盘,执行 shell 函数的最佳方式是什么?
// download a pdf and save to disk
// open pdf in osx preview for example
download_pdf()
.then(function(path) {
shell.exec('open ' + path).code !== 0);
});
function download_pdf() {
const path = '/local/some.pdf';
const url = 'http://somewebsite/some.pdf';
const stream = request(url);
const write = stream.pipe(fs.createWriteStream(path))
return streamToPromise(stream);
}
function streamToPromise(stream) {
return new Promise(function(resolve, reject) {
// resolve with location of saved file
stream.on("end", resolve(stream.dests[0].path));
stream.on("error", reject);
})
}
最佳答案
在这一行
stream.on("end", resolve(stream.dests[0].path));
您正在立即执行 resolve
,调用 resolve
的结果(这将是未定义的,因为那是 resolve
返回)用作 stream.on
的参数 - 根本不是您想要的,对吧。
.on
的第二个参数需要是一个函数,而不是调用函数的结果
因此,代码需要是
stream.on("end", () => resolve(stream.dests[0].path));
或者,如果你是老派:
stream.on("end", function () { resolve(stream.dests[0].path); });
另一种老派的方式是
stream.on("end", resolve.bind(null, stream.dests[0].path));
不,不要那样做 :p 查看评论
关于javascript - 在 node.js 中使用带有流的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44013020/