下一行执行尽管使用异步/等待

问题描述 投票:0回答:1

我试图让一个函数在阅读后续行之前解决一个承诺。 我期望的是:

START
promise resolved
line1
line2
line3
etc ...

但是,我得到的是在承诺解决之前我所有的台词都被阅读了

START
line1
line2
line3
promise resolved

我运行

npm index.js < input.txt
,其中包含:

START
line1
line2
line3

我有以下按行读取的主要功能。

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
  }
});

这是我调用以从我的 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;
};
javascript typescript asynchronous async-await readline
1个回答
0
投票

如果你不能使用

promise
版本的
readline
,你可以进行以下操作

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.