2

I have a function like:

function callApi(url){
    return fetch(url).then(response => {return response.json()}
       ).then(response => {return response})
}

function myFunction() {
    var status = null;
    while (status != "complete") {
        setTimeout(function(){
            callApi('myurl').then(response => {
               status = response.status
            }
         }, 5000)
    }

Here I simply want to check if I am getting desired status from the api call.

Untill I get desired status from the api call I want to check on every 5 seconds..

But this is not working.. I have googled but not understood the solution according to my need. It would be very helpful if anyone could answer this.

I am new to javascript. I have looked somewhere about es6 promise. It would be very great if someone could explain this ..

thank you

gamer
  • 5,673
  • 13
  • 58
  • 91
  • Have a look at [Correct way to write loops for promise](http://stackoverflow.com/q/24660096/1048572) – Bergi Mar 01 '16 at 22:54
  • You can (and should) completely omit `.then(response => {return response})`, the behaviour won't change a bit – Bergi Mar 01 '16 at 22:56

2 Answers2

1

Put this helper in all your scripts:

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

then never call setTimeout again (it has terrible error-handling characteristics).

Also, while is a synchronous construct, which wont work here. You could use asynchronous "recursion". Also, to sequence asynchronous operations, promises must be chained:

function myFunction() {
  return callApi('myurl').then(response =>
    response.status == "complete" ? response : wait(5000).then(() => myFunction()));
}
jib
  • 40,579
  • 17
  • 100
  • 158
0

The current code have some typos (missing closing braclets on the then and myFunction) and a big flaw.

setTimeout is not a blocking Function, so you are running in the while loop more times that you think. you are creating a LOT of 'later function' that will execute after 5 sec'.

right now, the flow of your code do this..

  1. WHILE ...
  2. CREATE A FUNCTION, BUT DONT RUN IT NOW ...
  3. RETURN TO THE WHILE ...

line 2 will run thousand of times even before the first 5 sec will pass..

Here is your code, without typos, but the main issue still remains.

function myFunction()
{
    var status = null;
    while (status != "complete")
    {
        setTimeout(function()
        {
            callApi('myurl').then(response => { status = response.status }); //<-- missing ')'
        }, 5000);
    }
}

as for the main problem, you should not write code that checks every X sec' if something happend, instead you shoud use the Promise API and add a function to the done event. that way your desired code will run only when the previous code in the asyncronous function finnished.

avrahamcool
  • 13,888
  • 5
  • 47
  • 58