The subsequent code still running even with the implementation of async/await

I'm currently facing an issue with a function that needs to resolve a promise before moving on to the next lines of code. Here is what I expect:

START
promise resolved
line1
line2
line3
etc ...

However, the problem I'm encountering is that all the lines are being read before the promise is resolved:

START
line1
line2
line3
promise resolved

The command I am using is npm index.js < input.txt, and the content of my input file includes:

START
line1
line2
line3

In my main function for reading lines, here's the logic I have implemented:

marker = true
rl.on("line", async (line: string) => {
  console.log(line);
  if (marker) {
    if (line === "START") {
      // Call API and wait for data to return before processing remaining lines
      let data = await getData();
      console.log("Promise resolved");
    }
    marker = false;
  } else {
    // Continue reading subsequent lines
  }
});

Here is the function responsible for fetching data from my API:

const getData = (): Promise<any> => {
  let response = null;
  const p = new Promise(async (resolve, reject) => {
    try {
      response = await axios.get(
        // URL and parameters go here
      );
    } catch (ex) {
      response = null;
      // Handle errors
      console.log(ex);
      reject(ex);
    }
    if (response) {
      // If successful, extract JSON data and resolve the promise
      const json = response.data;
      resolve(json);
    }
  });
  return p;
};

Answer №1

When the readline promise is not available, you have an alternative approach

let isActive = true;
let prom = Promise.resolve();
rl.on("line", (line) => {
    const functionAsync = async () => {
        console.log(line);
        if (isActive) {
            if (line === "START") {
                // make an API call and wait for the data before proceeding with other lines in the file
                let information = await fetchData();
                console.log("Promise resolved", information);
            }
            isActive = false;
        } else {
            // read next lines
        }
    };
    prom = prom.then(functionAsync);
});

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

javascript: obtain the height of the pseudo :before element

Can someone help me figure out how to get the height of a pseudo :before element? I've tried using jQuery but it's not working as expected. Here's what I attempted: $('.test:before').height() // --> null If you want to take a ...

issue occurring after inserting a new parameter

I encountered an issue with my test case after adding a new parameter tiger to the method swimming. Despite passing the new parameter tiger to my test case, it continues to break. Update: I am receiving an "undefined grid" error at this line. Any suggest ...

Dynamic Menu Navigation (No Bootstrap Required)

My Navbar is working perfectly in the original mode but when the screen width is less than 950px, it displays the buttons stacked vertically. However, the dropdown button opens the dropdown content on the wrong side. I want the dropdown content to appear u ...

The integration between Laravel and Vue.js seems to be causing issues with locating the CSS and JS files

I am currently working on a Laravel + Vue.js project that I need to enhance. Unfortunately, I cannot share the code due to NDA restrictions. The project consists of an API in Laravel and a front end in Laravel using Vue. After committing the project, updat ...

Angular Satellizer causing issues with Facebook login on mobile devices

Issue Currently, I'm developing an application using Angular and have successfully integrated Facebook login through Satellizer. The functionality works flawlessly on desktop browsers; however, when accessed from mobile devices, it tends to be unreli ...

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...

Retrieving and storing selected checkbox values using both JavaScript and PHP

I have location names and location IDs stored in a database table. I am using a foreach loop to print these values as checkboxes in PHP. When the user clicks on the submit button, it triggers a JavaScript function. I would like to store all the selected ...

Tips to prevent elements from overlapping in Angular applications

I am facing an issue with my Angular-based app where I dynamically populate the page with table rows. There is an app-console element below the page that has a fixed position. Whenever I click the button to add a new row, it overlaps with the app-console. ...

An unexpected import token was encountered while using ReactJS and Babel

Every time I attempt to launch my application, an error message pops up that says: (function (exports, require, module, __filename, __dirname) { import { Row } from '../grid' SyntaxError: Unexpected token import I've experimented with vari ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

What is the best way to conduct synchronous testing of animations in AngularJS version 1.3.15?

Encountering a migration issue with angular-animate.js while transitioning from version 1.2 to 1.3. Here is the animation code snippet: 'use strict'; angular.module('cookbook', ['ngAnimate']) .animation('.slide-down& ...

Understanding the time complexity of Object.entries()

Is the complexity of Object.entries() in JavaScript known? According to information from this question, it seems like it could possibly be O(n) if implemented by collecting keys and values as arrays and then combining them together? ...

How can I retrieve an image from a library and automatically update the image in SharePoint every 30 seconds?

I have a web part and I have written the code below: However, it is only fetching one image. How can I fetch all images from the library and change the image every 30 seconds using JavaScript or jQuery? public class MSDN : System.Web.UI.WebControls.WebPa ...

How to open a new window in a separate desktop on macOS using Javascript

I am currently browsing my website on a Mac computer. I am interested in opening a new tab on the second desktop using Mission Control. Is this achievable? If so, could you please guide me on how to do it? After searching extensively online, I have been u ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

Tips on using Bootstrap 4 containers within a container-fluid and ensuring text stays within a container at all times

What is the best way to incorporate a Bootstrap 4 container within a container-fluid? how can we ensure that text is always contained within the blue section? ...

Retrieving asynchronous data from a module and transmitting it via a route's endpoint

I'm currently in the process of constructing an API endpoint using Node. The goal is to retrieve data from an external API and then transfer this information through the created endpoint. Ultimately, this endpoint will be utilized on the client side. ...

Deactivate all functions of a complete row in the table

I'm working with a table that contains various user interaction controls in its cells, such as buttons and links. I'm looking to gray out certain rows of the table so that all operations related to those rows are disabled. Does anyone have sugge ...