0

I have a jquery method:

$.when(
  function() {
    console.log("1st Func!");
  },
  function() {
    console.log("2nd Func!");
  }
).done(function() {
  console.log("Done Func!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And I expect the first two method call and finished and at the end the done method run. I expect in console:

1st Func!
2nd Func!
Done Func!

But only the done method called and the console is like: Done Func!

Where is the problem?

UPDATE:

I get from the comments the function inside the When should be a promise. In actual sample I have:

var getAndSetFromAPI = function(keyName, callback){
    if (localStorage.getItem(keyName) === null){
        $.AjaxCall(.., .., callback(data));
    }
    else{
      if(callback){ callback(localStorage.getItem(keyName))}
    }
};

And I have a list of objects:

mylist.each(function (index, element){
      getAndSetFromAPI(element, function(date){fillData(element, data);}
});

So What is your suggestion to wait to complete each element and then go to process another one?

Saeid
  • 13,224
  • 32
  • 107
  • 173
  • 3
    you're passing in functions, but `when` doesn't call them for you – Jaromanda X Jul 05 '17 at 22:43
  • 5
    The arguments to `$.when()` are supposed to be promises, not functions. – Barmar Jul 05 '17 at 22:43
  • Your `getAndSetFromAPI` should not take a callback. It should return a promise. Always. – Bergi Jul 05 '17 at 22:55
  • See [Pass in an array of Deferreds to $.when()](https://stackoverflow.com/q/5627284/1048572) once you got `mylist.map(getAndSetFromAPI)` to produce an array of promises – Bergi Jul 05 '17 at 22:57
  • Why is this tagged [tag:async-await], can you use ES8 features and real promises? – Bergi Jul 05 '17 at 22:57

0 Answers0