0

I have an endpoint that generates some data (it takes some time) and another one that I can use to get the generated data. I call first one with await, take id from response, and want to call second one, while it status don't be "Success"(it mean data prepared and stored in response) and continue my script.

Here my code

let data = ['foo', 'bar']
let res = await client.post('ninbexec/v2/executions', data)
let result_id = res.data[0].id
while (true) {
        let resp = await client.get(`ninbexec/v2/executions/${result_id}`)

        if (resp.data.status === 'SUCCEEDED') {
            response = JSON.parse(resp.data.result.dataset)
            break;
        }
    }

it works, but I won to so much requests how can I set up some interval for requests? I tried with await setInterval(), but code continue execution and not wait for result

e.g. also I use axios, if it have some ballet in trick for that it will be more better

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Does this answer your question? [In JavaScript, does using await inside a loop block the loop?](https://stackoverflow.com/questions/44410119/in-javascript-does-using-await-inside-a-loop-block-the-loop) – Yasser hennawi Jun 03 '22 at 10:03

1 Answers1

2

You don't want to use setInterval for this case. You want to use setTimeout.

You cannot use setTimeout with await since it does not return a Promise.

It's an old API, and it uses a callback style, like this:

setTimeout(() => console.log('do something after 1000 ms'), 1000)

This is not very convenient if you want to use the await syntax.

What you can do is "promisifying" the setTimeout function, which means creating another version of the function that will be Promise based.

Sounds very fancy, but it's actually quite easy to do, here is an example:

function pSetTimeout(timeout){
  return new Promise((resolve) => {
    setTimeout(() => resolve(), timeout)
  })
}

It's just wrapping the call to setTimeout inside a Promise and calling resolve when the callback is called.

So your whole code would look like that:

let data = ['foo', 'bar']
let res = await client.post('ninbexec/v2/executions', data)
let result_id = res.data[0].id
while (true) {
    
    let resp = await client.get(`ninbexec/v2/executions/${result_id}`)

    if (resp.data.status === 'SUCCEEDED') {
        response = JSON.parse(resp.data.result.dataset)
        break;
    }
    await pSetTimeout(10000) // for exemple, wait for 10 seconds
}

Please make sure you understand completely what is a Promise based function and the difference between the old callback function style.