javascript - Chaining callbacks in a custom-made for-each loop, supporting both synchronous and asynchronous functions -


i have for_users function gets array of users web service, executes passed function f on received array, calls continuation f_then callback.

// execute f on every user, f_then. function for_users(f, f_then) {     // users database, in user_array     db.get_all_users(function(user_array)     {         // execute f on every user         user_array.foreach(f);          // call continuation callback         f_then();     }); } 

when calling for_users, passing asynchronous function f parameter, f callbacks end before calling f_then. not happening in current code, user_array.foreach(f) not wait f finish before starting next iteration.

here's example of problematic situation:

function example_usage() {     var temp_credentials = [];      for_users(function(user)     {         // credentials asynchronous function         // call passed callback after getting credential         // database         database.get_credentials(user.id, function(credential)         {             // ...         });     }, function()     {         // do_something call executed before callbacks         // have finished (potentially)          // temp_credentials empty here!         do_something(temp_credentials);     }); } 

how can implement for_users such if f asynchronous function, f_then called when f functions completed?

sometimes, though, passed f for_users not asynchronous , above implementation suffice. there way write generic for_users implementation work intended both asynchronous , synchronous f functions?

this should work you:-

function for_users(f, f_then) {    db.get_all_users(function(user_array) {       var promises = [];        user_array.foreach(function(user) {         promises.push(new promise(function(resolve, reject) {           f(user);           resolve();         }));       });        if (f_then)         promise.all(promises).then(f_then);       else         promise.all(promises);     }   }); } 

simple test below:-

function for_users(f, f_then) {    var users = [{id: 1}, {id: 2}, {id: 3}];    var promises = [];      users.foreach(function(user) {      var promise = new promise(function(resolve, reject) {        f(user);        resolve();      });      promises.push(promise);    })      if (f_then)      promise.all(promises).then(f_then);    else      promise.all(promises)  }    for_users(function(user) {    console.log(user.id);  }, function() {    console.log('finshed')  })


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -