Search code examples
javascripttypescriptasynchronousasync-awaitreadline

Next line executing despite using async/await


I am trying to make a function resolve a promise before reading in subsequent lines. What I expect is:

START
promise resolved
line1
line2
line3
etc ...

However, what I am getting is that all my lines are being read before the promise is resolved

START
line1
line2
line3
promise resolved

I run npm index.js < input.txt, which contains:

START
line1
line2
line3

I have the following main function that reads in lines.

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 executing other lines in the file
      let data = await getData();
      console.log("Promise resolved");
    }
    marker = false;
  } else {
    // read subsequent lines
  }
});

This is the function I'm calling to get results from my API

const async getData = (): Promise<any> => {
  let response = null;
  const p = new Promise(async (resolve, reject) => {
    try {
      response = await axios.get(
        // url and parameter information here
      );
    } catch (ex) {
      response = null;
      // error
      console.log(ex);
      reject(ex);
    }
    if (response) {
      // success
      const json = response.data;
      resolve(json);
    }
  });
  return p;
};

Solution

  • If you can't use the promise version of readline, you can do the following

    let marker = true;
    let promise = Promise.resolve();
    rl.on("line", (line) => {
        const fn = async () => {
            console.log(line);
            if (marker) {
                if (line === "START") {
                    // call API and wait for data to return before executing other lines in the file
                    let data = await getData();
                    console.log("Promise resolved", data);
                }
                marker = false;
            } else {
                // read subsequent lines
            }
        };
        promise = promise.then(fn);
    });