在Node.js中的流中使用Promise [英] Using promises with streams in node.js

查看:100
本文介绍了在Node.js中的流中使用Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重构了一个简单的实用程序来使用Promise.它从Web上获取pdf并将其保存到磁盘.一旦保存到磁盘,它将在pdf查看器中打开文件.该文件显示在磁盘上并且有效,shell命令打开OSX Preview应用程序,但是弹出对话框,提示该文件为空.

I've refactored a simple utility to use promises. It fetches a pdf from the web and saves it to disk. It should then open the file in a pdf viewer once saved to disk. The file appears on disk and is valid, the shell command opens the OSX Preview application, but a dialog pops up complaining that the file is empty.

将文件流写入磁盘后,执行shell函数的最佳方法是什么?

What's the best way to execute the shell function once the filestream has been written to disk?

// 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 的参数-完全不是您想要的,对吧.

you are executing resolve immediately, and the result of calling resolve (which will be undefined, because that's what resolve returns) is used as the argument to stream.on - not what you want at all, right.

.on 的第二个参数必须是 function ,而不是调用函数的结果

.on's second argument needs to be a function, rather than the result of calling a function

因此,代码必须为

stream.on("end", () => resolve(stream.dests[0].path));

或者,如果您是老学校:

or, if you're old school:

stream.on("end", function () { resolve(stream.dests[0].path); });

另一种老式的方法是

another old school way would be something like

stream.on("end",resolve.bind(null,stream.dests [0] .path));

不,不要那样做:p查看评论

No, don't do that :p see comments

这篇关于在Node.js中的流中使用Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆