简体   繁体   中英

Node.js - Getting return value from MySQL before proceeding

I am currently using node.js to communicate with my database. I'm having an issue where i want to wait for async database query before it continues.

I've tried many example from the internet and i can't seem to find the way to do it or the problem of it. What happened is that after the mysql query, it will proceed to the next line without waiting for the return value.

Here is my code:

 //Connection with database var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "justcall" }); console.log("before insert"); function queryPromise(str){ return new Promise((resolve, reject) => { con.query(str, (err, result, fields) => { if(err) reject(err); resolve(result); }) }) } async function run(){ let answer = await queryPromise("INSERT INTO calllog (userId, callId, timeCalled, callDuration, status, callType) VALUES ('27', '33', '2019-11-13 22:30:20', '00:00:01', '1', '1')"); console.log(answer); } run(); console.log("after insert");

Since run() is asynchronous, you need to wait for it.

run().then(function() { console.log("after insert"); });

If you call it from another async function, you can use await :

async function doit() {
    await run();
    console.log("after insert");
}
doit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM