1

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;

Meggy
  • 1,491
  • 3
  • 28
  • 63

2 Answers2

0

May I suggest you to use async await for this task? It will produce far more readable code. The logic will be as follows

var createAudiopost = async function(req, res, next){
 [...]
 
 let firstQueryResult = await mydb.query( str_sql_1 )
 if(shouldExecuteSecondQuery(firstQueryResult)) {
     let secondQueryInput = produceSecondQuery(firstQueryResult, str_sql_2)
     let secondQueryResult = await mydb.query( secondQueryInput )
     [...]
 }
 [...]
}

Adding a bit more context based on your code, I've skipped the parts that remain the same using [...]

var createAudiopost = async function(req, res, next){

[...]

let row_a, row_b, row_c, row_d, row_e, row_f;

try {

    row_a = await mydb.query( str_sql_1 )
     
    var audioname = userid + '-' + row_a[0].insertId + '.m4a';
    var newid = row_a[0].insertId;  

    rows_b = await mydb.query( str_sql_2 );

    rows_c = await mydb.query( str_sql_3 );
    const tagid1 = row_c[0]['tagid'];

    rows_d = mydb.query( str_sql_4 );
    const tagInsertId = row_d[0].insertId;

    //your condition
    if(tagInsertId) {
        rows_e = await mydb.query( str_sql_5 );    
    }
    else {
        rows_f = mydb.query( str_sql_6 );
    }
    console.log("success");
    res.json({
                    "title" : title, 
                    "userid" : userid,
                    "opid" : opid, 
                    "insertid": newid
                        });
}
catch(err) {
    console.log(err.message);
}
finally {
    mydb.close();
}

[...]
rm_
  • 707
  • 5
  • 5
  • Can you expand upon this a little bit? IE: Where do I add the If-Then statement? – Meggy Jun 28 '21 at 21:47
  • Edited the answer to include more of your code, see the comment in the if statement. This is where you should do your check and call the appropriate query conditionally. – rm_ Jun 28 '21 at 22:58
0

You can conditionally return the correct promise in the .then

  .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 tagInsertId ? mydb.query(str_sql_5) : mydb.query(str_sql_6)
  })
  .then(row => { ... })