React app can run node.js function which preparing data and sending information to the database in batches.
It takes a lot of time and I would like to add the ability to stop this function right from react app.
I tried a lot of things to include in this function including:
-
while loop: added the variable outside the function – if ‘true’ – run code, if not – return – it just doesn’t work (variable was changed from react using socket.IO)
-
setTimeout (also setInterval), triger clearTimeout function from react: this doesn’t work as setTimeout and setInterval doesn’t work in async function
after that:
- made (actually fond here on stackoverflow) new function to promisify setTimeout to be able to use in async function:
const setTimeout2 = (callback, ms) => {
return new Promise(
resolve =>
(to = setTimeout(() => {
callback();
resolve();
}, ms))
);
};
async function addOrdersToDB(limit) {
do {
await setTimeout2(async () => {
try {
// some code here
} catch (err) {
console.log(err);
}
}, 400);
} while (latestOrderExist);
}
function clearTO() {
setTimeout(() => {
console.log('clearTO');
clearTimeout(to);
}, 3000);
}
This for some reason doesn’t iterate.
Is there solution for this?
Thanks!