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