javascript - How to return the response of multiple asynchronous calls? -


similar question : return response async call except call within loop calls multiple time asynchronous function.

specifically, how can value of s returned? code returns undefined. function called within loop. library used orm bookshelfjs. help.

function getusernamefromdbasync(userid) {     var s = "moo";      new model.users({             iduser: userid         })         .fetch()         .then(function(u) {             var prenom = u.get('firstname');             var nom = u.get('familyname');             s = prenom + " " + nom;             return s;         }); } 

your aren't showing how you're doing loop makes little harder guess recommend. assuming .fetch().then() returns promise, here's general idea standard es6 promises built node.js:

function getusernamefromdbasync(userid) {     var s = "moo";      return new model.users({         iduser: userid     }).fetch().then(function (u) {         var prenom = u.get('firstname');         var nom = u.get('familyname');         s = prenom + " " + nom;         return s;     }); }  var userids = [...]; var promises = []; (var = 0; < userids.length; i++) {     promises.push(getusernamefromdbasync(userids[i])); }  // set .then() handler when promises done promise.all(promises).then(function(names) {     // process names array here }, function(err) {     // process error here }); 

if using bluebird promise library, little bit more this:

function getusernamefromdbasync(userid) {     var s = "moo";      return new model.users({         iduser: userid     }).fetch().then(function (u) {         var prenom = u.get('firstname');         var nom = u.get('familyname');         s = prenom + " " + nom;         return s;     }); }  var userids = [...]; promise.map(userids, getusernamefromdbasync).then(function(names) {     // process names array here }, function(err) {     // process error here }); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -