Javascript 异步/等待返回承诺{<;挂起>;}
我试图创建一个函数,它读取一个文件并返回一个散列,并且可以同步使用Javascript 异步/等待返回承诺{<;挂起>;},javascript,node.js,async-await,Javascript,Node.js,Async Await,我试图创建一个函数,它读取一个文件并返回一个散列,并且可以同步使用 export async function hash_file(key) { // open file stream const fstream = fs.createReadStream("./test/hmac.js"); const hash = crypto.createHash("sha512", key); hash.setEncoding("hex"); // once t
export async function hash_file(key) {
// open file stream
const fstream = fs.createReadStream("./test/hmac.js");
const hash = crypto.createHash("sha512", key);
hash.setEncoding("hex");
// once the stream is done, we read the values
let res = await readStream.on("end", function() {
hash.end();
// print result
const res = hash.read();
return res;
});
// pipe file to hash generator
readStream.pipe(hash);
return res;
}
看来我把等待关键字放错了
如果wait运算符后面的表达式的值不是
承诺,这是一个坚定的承诺
readStream.on
不会返回承诺,因此您的代码无法按预期工作
不要使用wait
,而是将readStream.on
包装在Promise
中,并在其结束时解决
function hash_file(key) {
// open file stream
const readStream = fs.createReadStream("./foo.js");
const hash = crypto.createHash("sha512", key);
hash.setEncoding("hex");
// once the stream is done, we read the values
return new Promise((resolve, reject) => {
readStream.on("end", () => {
hash.end();
// print result
resolve(hash.read());
});
readStream.on("error", reject);
// pipe file to hash generator
readStream.pipe(hash);
});
}
我试图创建一个函数,它读取一个文件并返回一个散列和
可同步使用的
这永远不会发生。不能使异步代码同步。您可以使用async/await
使它看起来像是同步的,但它始终是异步的
(async() => {
const hash = await hash_file('my-key'); // This is async.
console.log(hash);
})();
你的问题到底是什么?好吧,如果
readStream.on
返回一个承诺。。。你将永远无法同步使用这些代码<代码>流是异步的。任何包含承诺的函数都会返回承诺async/await
并不是消除这一点的“魔法”,它只是编写比使用then()
更自然的流的“糖”readStream
是一个“流”,而不是承诺。您可以wait
此hash_文件
函数来解析何时触发“stream”end
事件,如果这是您真正想要的。但是这里没有“返回值”,所以不清楚您期望的是什么。您永远无法使异步结果同步可用。从未。async
函数总是返回一个承诺,而await
只在等待的东西是承诺时才等待readstream.on()
没有回报承诺,所以你的wait
没有任何用处。好吧,你们真的把我踩在地上了,伙计们。。我想做的只是从这个函数中得到一个散列。。。