I'm just learning to use promises for my NodeJS MySQL queries. But I don't understand how to use IF THEN ELSE statements as a conditional to the next query. I basically need to check str_sql_4
for a tag. If it doesn't exist str_sql_6
is queried ELSE if it does existstr_sql_5
is queried. I left out prepared statements at the moment as I'm just trying to get my head around the promises way of doing things.
Here's as far as I've gotten with the code;
var createAudiopost = function(req, res, next){
var title = req.body.title;
var userid = req.body.userid;
var opid = req.body.opid;
var tag1 = req.body.tag1;
var tag2 = req.body.tag2;
var tag3 = req.body.tag3;
var str_sql_1 = 'INSERT INTO audioposts (title,userid,opid) VALUES (title,userid,opid )'; //, ['audioposts',title,userid,opid]';
var str_sql_2 = 'UPDATE audioposts SET audioname=audioname WHERE audioid = newid';
var str_sql_3 = 'SELECT tagid FROM tags WHERE tagname = tag1';
var str_sql_4 = 'INSERT INTO tags SET tagname = tag1';
var str_sql_5 = 'INSERT INTO entitytag SET audioid = newid, tagid = tagInsertId, userid = userid";
var str_sql_6 = 'INSERT INTO entitytag SET audioid = newid, tagid = tagid1, userid = userid";
let mydb = new Database(config);
let row_a, row_b, row_c, row_d, row_e, row_f;
mydb.query( str_sql_1 )
.then( rows => {
row_a = rows;
var audioname = userid + '-' + row_a[0].insertId + '.m4a';
var newid = row_a[0].insertId;
return mydb.query( str_sql_2 );
} )
.then( rows => {
row_b = rows;
return mydb.query( str_sql_3 );
} )
.then( rows => {
row_c = rows;
const tagid1 = row_c[0]['tagid'];
return mydb.query( str_sql_4 );
} )
.then( rows => {
row_d = rows;
const tagInsertId = row_d [0].insertId;
return mydb.query( str_sql_5 );
} )
.then( rows => {
row_e = rows;
return mydb.query( str_sql_6 );
} )
.then( rows => {
row_f = rows;
return mydb.close();
} , err => {
return mydb.close().then( () => { throw err; } )
})
.then( () => {
// do something with someRows and otherRows
console.log("success");
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid
});
}).catch( err => {
console.log(err.message);
}
);
} //createaudiopost
module.exports = createAudiopost;
So can I use IF THEN ELSE statements somewhere or is there another way I should execute conditional queries?
Also how can I fetch the last insertID? This gives an undefined error; var newid = row_a[0].insertId;