gpt4 book ai didi

node.js - 异步/等待 : Understanding problem with Async/Await

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:45 24 4
gpt4 key购买 nike

我正在使用异步/等待。我想先显示从可读流中检索到的数据,然后显示相应的消息;

这是我的代码:

var stream = async function (){
var myStream = fs.createReadStream(__dirname+"/someText.txt",'utf8');

await myStream.on('data', (chunk)=>{
console.log(chunk)// I want to display this first
})
}

stream()

console.log('listening') // and then move on to display this one

最佳答案

流监听器不是 promise ,您不应该在 myStream.on('data')await。你可以这样做,但它会立即解决。

将流监听器包装在 Promise 中并等待它,为此您可以使用 once

const { once } = require('events');

var stream = async function (){
var myStream = fs.createReadStream(__dirname+"/someText.txt",'utf8');

myStream.on('data', (chunk) => {
console.log(chunk)// I want to display this first
});

// Wait until everything has been read
// Or an error has been triggered
await once(myStream, 'close');
}

(async() => {
await stream(); // await can only be used in `async` function
console.log('listening');
})().catch(console.error);


关于node.js - 异步/等待 : Understanding problem with Async/Await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com