async/
await仅适用于promise,不适用于流。有一些想法可以制作一种类似流的额外数据类型,该数据类型将具有自己的语法,但是如果有的话,这些想法是高度实验性的,我将不赘述。
无论如何,您的回调仅等待流结束,这非常适合兑现承诺。您只需要包装流:
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 objectfd.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);}());
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)