0

I have 2 variable and i want to do something when they changed to same value like each other. So this is my code:

var val_1,val_2;
for(i=0;i<=5;i++){
    readyforgo++;
    $.post("somewhere.php",{
        something: something
    },function(data, status){
        readytogo++;
    });
}
if(readyforgo==readytogo){
    alert(1);
}

Its not gonna return 1 because my if is working faster than my $.post i mean i want some code like this :

function checker(){
    if(readyforgo==readytogo){
        alert(1);
    }else{
        setTimeout(function(){checker();},100);
    }
}
checker();

Its working as well but i looking for something better i mean i don't want to use any code like that because its using cpu and ram until trying to get readyforgo==readytogo do we have code like this? i don't like to use setTimeout or setInvertal or something like that.

2 Answers2

1

You could use Promise.all(promises).

  • Your $.post would need to be adapted to create a promise unless it already returns one. (See comment from georg)
  • You would put each promise into an array.
  • Promise.all will be invoked after all async calls complete.
const promises = []
for(let i=0; i<5; i++){
  // assuming your post returns a promise
  promises.push($.post("somewhere.php"))
}
Promise.all(promises).then(results=>{
  // your code here
})

If your code is in an async block, you can do the following and avoid nested functions:

results = await Promise.all(promises)
// your code here
})

This pattern of waiting on all promises is very common after dispatching multiple async calls.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • 1
    @Andy for the record, One can use promisify or a simple manual wrapper. I could post it, but there are many solutions for that on SO. And as it turns out, not needed in this case. – Steven Spungin Sep 21 '19 at 11:31
  • `Promises.all` is not working but `Promis.all` is working –  Sep 28 '19 at 06:38
0

If you want to check when all the posts have either been resolved/rejected you could take advantage of how jQuery's deferred objects (similar to promises) work. Create an array of jQuery deferred objects and then use when to wait until they've all resolved/rejected.

// Create an array of POST deferred objects
function getDeferreds() {
  const deferreds = [];
  for (let i = 0; i <= 5; i++) {
    deferreds.push($.post("somewhere.php", { something: something }));
  }
  return deferreds;
}

// $.when works similarly to Promise.all
$.when.apply(null, getDeferreds()).then(data => {
  alert(1);
});

Here's a good explanation why apply has been used in this example.

Andy
  • 61,948
  • 13
  • 68
  • 95