G
G
gomerIT2021-01-27 17:47:46
JavaScript
gomerIT, 2021-01-27 17:47:46

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

Can you tell me how to solve this problem or some other solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gomerIT, 2021-01-27
@gomerIT

Thanks Vasily for the tip. Wrote this function

sleep = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));

V
Vasily Bannikov, 2021-01-27
@vabka

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 question

Ask a Question

731 491 924 answers to any question