Your code is blocking not due to do... while..
. Its due to the async await
.
Sample blocking code.
async function resolveAfterSomeTime() {
let counter = 0;
do {
console.log("starting promise")
const x = await new Promise(resolve => {
setTimeout(function () {
resolve("done")
console.log("promise is done")
}, 800)
});
counter++;
console.log(x);
} while (counter < 5);
}
resolveAfterSomeTime();
As you can see the above code is blocking for 800 milli second for each execution due to async await
.
You can make this non blocking by simply removing async await
. If you are not interested in the result, you can simply call the function and go for the next iterearion. Here in the below code, the value for x
will be a promise, you can check the resolved status of the promise to handle your further logic using x.then((resp) => console.log(resp))
Sample code.
function resolveAfterSomeTime() {
let counter = 0;
do {
console.log("starting promise")
const x = new Promise(resolve => {
setTimeout(function () {
console.log("promise is done");
resolve("done");
}, 800)
});
counter++;
x.then((resp) => console.log(resp))
} while (counter < 5);
}
resolveAfterSomeTime();
Your sample non blocking code
let scoring_report;
let timeout_count = 1;
let getReport;
do {
new Promise((resolve) => setTimeout(resolve, timeout_count * 1000));
// here getReport will be a promise
getReport = axios.post(`${process.env.SERVICE_PATH}:8001`, { body });
// Use getReport.then((data) => {}) for further logic
} while (!scoring_report);
Implementation using setInterval
If you just want to execute the function on the specified interval, you can make use of setInterval
which will not block your main thread. Donot forget to clearInterval
once the required result is available.
Sample Implementation
let scoring_report;
let timeout_count = 1;
let getReport;
const myInterval = setInterval(() => {
getReport = await axios.post(`${process.env.SERVICE_PATH}:8001`, { body });
scoring_report = getReport.data.data.reportBase64;
timeout_count += 2;
if(scoring_report) {
clearInterval(myInterval)
}
}, timeout_count * 1000);