Basically I need to wait the result of the insert
query made with Bookshelf.js
, because I need the id provided by the query to insert a row in my DB
I don't understand some aspects of the asynchronous behavior of Node and its components
So the problem is in this part of the code:
Insert Method Bookshelf
var new_timer = new Timer({
titolo: title,
time: timerVal,
created: creation,
ended: ended,
id_owner: owner
});
new_timer.save(null, {method: "insert"}).then(function(model){
if(!model)
return res.send({status: 400, url: "/add"});
associateTag(model.id_timer, tags);
return res.send({status: 200, url: "/"});
});
functions used
var insertAssociation = function(timerID, tags) {
return knex.table('timer_tag').insert({id_tmr: timerID, id_tg: tags.id_tag});
}
var associateTag = function(timerID, tags) {
var id_tag;
for(var i = 0; i < tags.length; i++){
getTagByName(tags[i]).then(function(result) {
console.log(result);
insertAssociation(timerID, result[0]).then(function(k) {
console.log(k);
});
});
}
}
var getTagByName = function(name) {
return knex.table('tags').select('id_tag').where('nome_tag', name);
}