Reputation: 8376
I'm having MULTIPLE problems while using sails because I can't understand waterline promises and its logic.
I tried both built in bluebird promises and also even a async.waterfall
implementation and couldn't succeed.
In a few words, I'm writing code for an API which performs db queries and by triying to use callbacks, it's Never responding.
This is what I 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 a formation was previously 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 this above I can see in console "Never reached"
. Why!?
And this is what I 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 a 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 any of rule restrictions evaluates to true ...
// Using lodash _.some with out second argument which defaults to _.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 to respond");
if (err)
respond.send(500);
else
response.send(result.status, result.msg);
});
console.log("Never reached");
},
This gives not a timeout but it's strangely not updating the document when it should. It's logging "never reached"
and then "about to respond"
but that's normal I guess.
So far, how should I handle it all?
Upvotes: 2
Views: 198
Reputation: 2082
In this above I can see in console "Never reached". Why!?
Because you're mixing async code with sync'd code. If you 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 the async code will be executed afterwards. I suggest you read this and this to better understand async callbacks.
This gives not a timeout but it's strangely not updating the document when it should.
It's hard to say what's going on because we don't know the model definition of LineUp
and we don't know the contents of lineup
before and after the update
call. Are you sure that LineUp.update()
ran? Why not adding a console.log()
in its callback to see the result?
So far, how should I handle it all?
It seems to me you're close to achieving your goal. If you share the LineUp
's model definition and some more logging we'll be able to help you more.
Upvotes: 2