Answer the question
In order to leave comments, you need to log in
How to execute setTimeOut inside while in NodeJS?
I make a request to the server and get a response, at a certain value I have to make a request to the server again, but wait a little before that. For some reason my code doesn't work the way I wanted.
let code = await sms.getStatus(id);
if (code.status === 'error') {
console.log(code.message);
}
while (code.status === 'warn') {
console.log('Код еще не пришел, жду 7 секунд');
setTimeout(async () => {
code = await sms.getStatus(id);
}, 7000);
}
Answer the question
In order to leave comments, you need to log in
Thanks Vasily for the tip. Wrote this function
sleep = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));
setTimeout is executed asynchronously.
You can solve this in two ways:
1. Refuse the loop and use recursion
2. Wrap setTimeout in a promise and use await
(I will write an example a little later)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question