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

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

The Influence of Getter Performance in Angular Templates

As I delve into an existing Angular application, I've noticed a pattern where values used in templates across many components are actually properties that are being accessed through getters and setters without any additional logic: <input type="nu ...

Primeng - Concealed dropdown values within a scrollable table header

Recently, I integrated Primeng p-table with a filter and frozen column feature (with one column being fixed while the others are movable). However, I encountered an issue with the select dropdown in the header. When I try to open the dropdown, the values a ...

issue connecting asynchronous pipe inside a custom directive input

There seems to be a bit of an issue! I have a custom directive that adds a hidden attribute based on input provided. import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core'; @Directive({ selector: '[ticketingPrim ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...

How to assign a click event to dynamically generated HTML elements using jQuery

My goal is to attach an onclick event to a dynamically inserted element using jQuery However, I am facing an issue where the function does not execute. I would appreciate it if someone could help me determine why this example is not functioning correctly ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

Using async/await in a POST handler within Express.js

My goal is to invoke an async function within a POST handler. The async function I'm trying to call looks like this (the code is functional): const seaport = require("./seaport.js"); // This function creates a fixed price sell order (FPSO) ...

Is there a callback or event that can be used to ensure that getComputedStyle() returns the actual width and height values?

Currently, I find myself in a situation where I need to wait for an image to load before obtaining its computed height. This information is crucial as it allows me to adjust the yellow color selector accordingly. Question: The process of setting the yello ...

What is the best way to store values in a map for future reference within a Kotlin class?

Looking to implement a map of key value pairs in Kotlin inside a class that is mutable and can be updated and referenced as needed. Research suggests that using a MutableMap would be the appropriate choice, given its ability to be updated at any point. I ...

Is it possible to pass a number instead of a string to Angular's matToolTip within a mat-icon-button? If not, is there a way to convert the number to a string within an Angular

In my current situation, I am facing a challenge with the following line of code: [matTooltip]="ratingId + 1". This line is crucial as it forms part of the arguments for a Material Design button. However, in this case, things are not straightfo ...

Enhancing Real-time Communication with NodeJS and NowJs Servers

Recently, I stumbled upon NodeJS and NowJS and I'm fascinated by the technology. My goal is to develop a Facebook-style instant commenting application where users can post comments that will instantly appear on the feed. After watching the screencast ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

Issue with ReactJS Typescript: Cannot assign type 'number' to type '0, 8, 16, 24, 32, 40, or undefined'

I am looking to implement a grid from material-ui in react using typescript. You can view the live demo here. I have made adjustments to the example to make it work with typescript. Here is how my demo.jsx file looks like: import { withStyles } from &apo ...

TypeORM issue - UnsupportedDataTypeError

Here is the entity file I'm working with, user.ts: @Entity('users') export class User { @PrimaryGeneratedColumn() id: number | undefined; @Column({ type: 'string', name: 'username', nullable: true }) username: s ...

Error message: The method app.get() is invalid as it is not a

I'm having trouble using Express in a prototype function ioServer() { } module.exports = ioServer; ioServer.prototype.start = function() { var app = require('express') var http = require('http').Server(app) ...