javascript - How should I handle promises and callbacks with waterline and bluebird? -


i'm having multiple problems while using sails because can't understand waterline promises , logic.

i tried both built in bluebird promises , async.waterfall implementation , couldn't succeed.

in few words, i'm writing code api performs db queries , triying use callbacks, it's never responding.

this tried on pure promises:

changeformation: function (request,response) {    console.log("changeformation");   var lineupid = request.params.id;   var newformation = request.param('formation');   var newlineup = request.param('lineup');   console.log("receiving" + newformation);    if ( ["5-4-1", "5-3-2", "4-5-1", "4-4-2", "4-3-3", "3-5-2", "3-4-3"].indexof(newformation) === -1 ) {     console.log("no válida");     return response.send(409, "la táctica elegida no es válida");   }    lineup.findone({id: lineupid}).   then(function (foundlineup) {      console.log(foundlineup);     if (!foundlineup)       return response.send(404);      if (! foundlineup.formation) {        foundlineup.formation = newformation;      lineup.update({id: foundlineup.id}, foundlineup).exec(function (err, saved) {        if (err)         return response.send(500, json.stringify(err));        return response.send(202, json.stringify(saved));     });      }      // if formation set     else if (array.isarray(newlineup) &&  newlineup.length > 0) {        newlineup.formation = newformation;        lineup.update({id: newlineup.id}, newlineup).exec(function (err,saved) {         if (err)           return response.send(500,json.stringify(err));         return response.stringify(202, json.stringify(saved));       });     }     console.log("never reached");   }).   catch(function (err) {     console.log(err);     response.send(500,json.stringify(err));   }); }, 

in above can see in console "never reached". why!?

and tried using async module:

addplayer: function (request,response) {    // console.log("add player");   var lineupid = request.params.id;    var receivedplayer = request.param('player');   var playerid = receivedplayer.id;   var bench = receivedplayer.bench;   var place = receivedplayer.place;   var e, r;    async.waterfall([      function (cb) {        lineup.findone().where({id: lineupid}).exec(function (err, foundlineup) {         cb(err,foundlineup);       });},      function (lineup,cb) {        player.findone().where({id: playerid}).exec(function (err,foundplayer) {         cb(err,lineup, foundplayer);       });},      function (lineup, player, cb) {       if (!player) {         console.log("jugador no existe");         cb(null, {status: 409, msg: "el jugador " + playerid + " no existe"});       }        if (!lineup.formation) {         console.log("no hay táctica")         cb(null, {status: 409, msg: "no se ha elegido una táctica para esta alineación"});       }        if (lineup.squadiscomplete()) {         console.log("ya hay 15");         cb(null, {status: 409, msg: "la plantilla ya contiene el máximo de 15 jugadores"});       }        if (lineup.playerwasadded(player.id)) {         console.log("jugador ya en alineación")         cb(null, {status: 409, msg: "el jugador ya ha sido agregado la alineación"});       }        if (lineup.fieldiscomplete() && !bench) {         console.log("ya hay 11 en el campo");         cb(null, {status: 409, msg: "ya se han agregado los 11 jugadores de campo"});       }        player.bench = bench;       player.place = place;        lineup.players.push(player);        console.log("maxforeign " + lineup.reachesmaxforeignplayers());       console.log("budgetlimit " + lineup.reachesbudgetlimit());       console.log("sameteam " + lineup.reachesmaxsameteamlimit());       console.log("reachesmaxsamefavoriteteamlimit " + lineup.reachesmaxsamefavoriteteamlimit());         // if of rule restrictions evaluates true ...       // using lodash _.some out second argument defaults _.identity /*      if ( _.some([ lineup.reachesmaxforeignplayers(),                     lineup.reachesbudgetlimit(),                     lineup.reachesmaxsameteamlimit(),                     lineup.reachesmaxsamefavoriteteamlimit()]) ) {          return response.send(409, "la inclusión de este jugador no satisface las reglas del juego");       }*/        lineup.update({id: playerid}, lineup).exec(function (err, saved) {         cb(err, {status: 202, msg: json.stringify(saved)});       });     }   ],    function (err, result) {     console.log("about respond");     if (err)       respond.send(500);     else       response.send(result.status, result.msg);   });    console.log("never reached"); }, 

this gives not timeout it's strangely not updating document when should. it's logging "never reached" , "about respond" that's normal guess.

so far, how should handle all?

in above can see in console "never reached". why!?

because you're mixing async code sync'd code. if do:

function(){   console.log('init');   someasyncmethod(function callback(){     return console.log('async done');   });   console.log('never reached'); } 

you'll get:

init never reached async done 

because async code executed afterwards. suggest read this , this better understand async callbacks.

this gives not timeout it's strangely not updating document when should.

it's hard what's going on because don't know model definition of lineup , don't know contents of lineup before , after update call. sure lineup.update() ran? why not adding console.log() in callback see result?

so far, how should handle all?

it seems me you're close achieving goal. if share lineup's model definition , more logging we'll able more.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -