异步/等待:了解异步/等待问题

时间:2019-11-30 21:40:43

标签: node.js express asynchronous async-await node-modules

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

这是我的代码:

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 

1 个答案:

答案 0 :(得分:2)

流监听器不是承诺,您不应该awaitmyStream.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);