Home > other >  NodeJS : wait for a variable to be created before calling a function
NodeJS : wait for a variable to be created before calling a function

Time:11-13

I am kinda new to NodeJS, and working an API for a personnal project. I need to create accounts in a db and then send a confirmation email to the people. So, the route to create an account starts by inserting the data in a database, then getting the insertedId to create a token, and then send a confirmation email with the token inside of it.

I am using db.query() from the mysql package (version 2.18.1) to interact with the database, which is a MySQL database from GCloud:

db.query("INSERT INTO user SET ?", [data], async (iErr, result) => {
    if (iErr) {
        res.status(410).jsonp({msg:iErr});
        next(iErr);
    } else {
        const insertedId = result.insertId;
        let emailToken = await getEmailToken(insertedId);
        // then sending the email using another async method
    }

However, the token sent do no have the id inside of it, like if the getEmailToken() used 'undefined' as a parameter.

Does anyone now a solution ?

Thank you.

EDIT : The same issue appears inside of the email, where I put the req.body.name. It is sent as « undefined » in the email, but it is given while calling the route (I store it in the database).

CodePudding user response:

If you use mysql package, according to doc, db.query's callback get 3 parameters first error second result third fields.Like so:

db.query("INSERT INTO user SET ?", [data], async (err, result, fields) => {}

CodePudding user response:

The mysql package README documents the way to obtain the newly-inserted ID: https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row

There are several problems with the callback in your code:

  • It looks like the order of the arguments may be wrong - the documentation has it like this - notice how the results object is the second argument, not third. So, you may be getting "result" under "rows".

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields)

  • The mysql library uses insertId. This is easy to mistake for insertedId, which is used in MongoDB, but they are not the same word.
  • Related