如何使用ES8异步/等待与流?
在。
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);
但有可能将其转换为使用异步ES8 /伺机而不是使用回调如上可见,但同时仍保持使用流的效率?
回答如下:async
/ await
只与承诺,不适用于流。有想法,使额外的流式数据类型将获得它自己的语法,但这些都是在所有如果处在实验阶段,我就不赘述了。
总之,您的回调只是等待流,这是一个承诺完美契合的结束。你只需要换流:
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
// read all file and pipe it (write it) to the hash object
fd.pipe(hash);
var end = new Promise(function(resolve, reject) {
hash.on('end', () => resolve(hash.read()));
fd.on('error', reject); // or something like that. might need to close `hash`
});
现在,你可以等待这一承诺:
(async function() {
let sha1sum = await end;
console.log(sha1sum);
}());
如何使用ES8异步/等待与流?
在。
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);
但有可能将其转换为使用异步ES8 /伺机而不是使用回调如上可见,但同时仍保持使用流的效率?
回答如下:async
/ await
只与承诺,不适用于流。有想法,使额外的流式数据类型将获得它自己的语法,但这些都是在所有如果处在实验阶段,我就不赘述了。
总之,您的回调只是等待流,这是一个承诺完美契合的结束。你只需要换流:
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
// read all file and pipe it (write it) to the hash object
fd.pipe(hash);
var end = new Promise(function(resolve, reject) {
hash.on('end', () => resolve(hash.read()));
fd.on('error', reject); // or something like that. might need to close `hash`
});
现在,你可以等待这一承诺:
(async function() {
let sha1sum = await end;
console.log(sha1sum);
}());