Navigating the complexities of Async/Await: Exploring the challenges of Async/Await

Utilizing async/await, I aim to showcase the data obtained from a readable stream prior to displaying the corresponding message.

Below is my code snippet:

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

            await myStream.on('data', (chunk)=>{
             console.log(chunk)// This content should be displayed first
        }) 
 }

stream()

console.log('listening') // Subsequently, this message will be shown

Answer №1

Rather than waiting for promises, be cautious of using await with myStream.on('data'). Although possible, it will essentially resolve instantaneously.

To properly handle stream listeners with promises, encapsulate the listener in a Promise and await its resolution using once

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

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

    myStream.on('data', (chunk) => {
       console.log(chunk)// Displaying first
    });

    // Waits until all data is read or error occurs
    await once(myStream, 'close'); 
}

(async() => {
  await processDataFromStream(); // `async` function required for `await`
  console.log('listening');
})().catch(console.error);


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid using cookies for tracking purposes

I've set up basic authentication, which is working fine in my localhost environment. However, when I try to run the same setup in production, the registration process works but the cookie isn't getting assigned to the client site. Client side: ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

The cPanel Node.js application is experiencing difficulties connecting to the MongoDB Atlas cluster, yet it functions without any issues on

Having developed a website using Node.js with MongoDB Atlas as the database, I encountered no issues while testing it on Heroku. However, after purchasing my domain and switching to proper hosting, I faced challenges. I attempted to set up my website by c ...

What methods are available to expedite webpack compilation (or decouple it from server restart)?

My current setup includes the following configurations: import path from 'path' import type {Configuration} from 'webpack' const config: Configuration = { mode: 'development', entry: path.join(__dirname, '../..&apos ...

Troubleshooting problems with deploying an Angular app on Heroku

When I attempt to deploy my Angular app on Heroku, I am running into a 'Not found' error and getting additional information in the console ("Failed to load resource: the server responded with a status of 404"). Below is the entire Heroku build l ...

Global installation of Node app causes discrepancies in processing of escape characters within paths

I'm completely new to Node.js, so I'm sure there's a straightforward answer to this question... I'm working on an app that requires a file path input. This path is generated by dragging a file into the Terminal window, resulting in a p ...

Running socket.io and express simultaneously on an elastic beanstalk instance: A step-by-step guide

We are running an Elastic Beanstalk instance with both REST services and Socket.io. Our Express server is configured to start at port 80, while the Socket.io connection is set up on port 3001. Despite turning off the proxy from nginx to disable it, we ar ...

What is the best way to transform a GET request with a query string into a promise?

After successfully making a request with querystring params, I encountered an issue while trying to promisify my request: // Works var Promise = require("bluebird"); var request = Promise.promisifyAll(require("request")); request.get({ url: 'htt ...

What steps can be taken to troubleshoot and resolve the API problem causing a 400 error in a react

I'm currently working on my react project and attempting to add a new page. I've set up all the models, controllers, and routes, but unfortunately, the data from the form on my newly added page isn't being posted into the MongoDB collection. ...

Tips for fixing the node.js "JavaScript heap out of memory" issue

I've encountered an issue while running a node.js service on my Ubuntu 16.04 server. The error message I'm seeing is: "UFATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory". After doing some research, I found on St ...

Heroku (Node application): What is the fate of temporary files on the platform?

My Node application, which is hosted on a free Heroku account, utilizes Amazon S3 to store files. I am currently using the s3fs module in conjunction with multiparty middleware to first temporarily store files before uploading them to S3. However, even af ...

What is the proper way to gracefully stop a koajs server?

Is there a way to gracefully stop koajs like I've seen for expressjs? I also need to disconnect database connections during the process. Specifically, I have a mongoose database connection and 2 oracle db connections (https://github.com/oracle/node- ...

Why is it that npm installs multiple versions of the same dependency when they are installed individually?

Scenario 1 Environment: Windows System Command Prompt (cmd) Node Version: v8.0.0 NPM Version: v5.5.1 In the given package.json file, I have explicitly listed: "@swimlane/ngx-charts": "^7.3.0", "@swimlane/ngx-graph": "^4.3.0", These packages have a de ...

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

The fatal error encountered was completely unexpected: an Uncaught UnexpectedValueException was thrown due to the server returning an unprecedented value. The anticipated response was "HTTP/1.1 101", but instead, an

I am completely new to using socketIO and elephantIO. Currently, I'm attempting to emit data from a PHP file called "emit_test.php" to a node server. Here's the code snippet I've been working with: ini_set("display_errors",5); include ("v ...

Encountering a Sequelize error message that reads "Invalid value" while executing a basic query

After successfully creating a user with sequelize, I encountered an issue where querying any user resulted in an "Invalid value" error. The Sequelize User model is defined as follows: import DataTypes from "sequelize"; import bcrypt from "b ...

Issue encountered during deployment on Google App Engine

I've been encountering an issue while trying to deploy my Node.js application with MySQL Backend to Google App Engine. I am utilizing Sequelize ORM and have both the Cloud SQL Instance and App Engine within the same project. However, upon attempting t ...