我正在使用异步/等待。我想先显示从可读流中检索到的数据,然后显示相应的消息;
这是我的代码:
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
答案 0 :(得分:2)
流监听器不是承诺,您不应该await
上myStream.on('data')
。您可以做到,但是它将立即解决。
将流监听器包装在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);