如何使用异步ES7 /等待与流? [英] How to use ES7 async/await with streams?
问题描述
在 http://stackoverflow.com/a/18658613/779159 是如何计算的MD5为例使用文件的内置加密库和溪流。
In http://stackoverflow.com/a/18658613/779159 is an example of how to calculate the md5 of a file using the built-in crypto library and streams.
var fs = require('fs');
var crypto = require('crypto');
// the file you want to get the hash
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
fd.on('end', function() {
hash.end();
console.log(hash.read()); // the desired sha1sum
});
// read all file and pipe it (write it) to the hash object
fd.pipe(hash);
但是,它可以将其转换为使用ES7异步/等待,而不是使用回调如上可见,但同时仍保持使用流的效率?
But is it possible to convert this to using ES7 async/await instead of using the callback as seen above, but while still keeping the efficiency of using streams?
推荐答案
异步
/ 等待
只适用于诺言,不与流。有想法,使额外的流式数据类型将获得它自己的语法,但这些都是高度,如果实验在所有我不会赘述了。
async
/await
only works with promises, not with streams. There are ideas to make an extra stream-like data type that would get its own syntax, but those are highly experimental if at all and I won't go into details.
总之,你的回调只是等待流,这是一个承诺的完美契合的结束。你只需要换流:
Anyway, your callback is only waiting for the end of the stream, which is a perfect fit for a promise. You'd just have to wrap the stream:
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
fd.on('end', function() {
hash.end();
});
// read all file and pipe it (write it) to the hash object
fd.pipe(hash);
var end = new Promise(function(resolve, reject) {
fd.on('end', ()=>resolve(hash.read()));
fd.on('error', reject); // or something like that
});
现在,你可以等待这个承诺:
Now you can await that promise:
(async function() {
let sha1sum = await end;
console.log(sha1sum);
}());
这篇关于如何使用异步ES7 /等待与流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!