javascript - Wait for async .done() in every iteration of loop -


so, have function locks this:

function getmaindata() {     var dfd = $.deferred();      $.getjson('my string pass',         function(result) {             if (result !== undefined) {                 dfd.resolve(result);             }         })      return dfd.promise() }  function getspecificdata() {     var dfd = $.deferred();      var myarray = [];      (var = 0; < 5; i++) {         getmaindata().done(function(result) {             myarray.push(result)              dfd.resolve(myarray) //this lost.         })     }      return dfd.promise() }  getspecificdata().done(function(result) {     console.log(result); }) 

i think know how promises work if chain them can not make for-loop wait async call finish before next iteration.

can please me?

a loop has no means of delaying next iteration wait asynchronous code.

you can solve using function called recursively instead

function getmaindata() {     return $.getjson('my string pass'); }  function getspecificdata() {     var myarray = [], def = new $.deferred();      (function rec(i) {         getmaindata().done(function(result) {             myarray.push(result);             if (i < 5 && result !== undefined) {                 console.log(i)                 rec(++i);             } else {                 def.resolve(myarray);             }         });     })(0);      return def.promise(); }  getspecificdata().done(function(result) {     console.log(result); }); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -