nodejs로 간단한 API를 만들려고합니다. 그러나 나는 nodejs가 SQL 쿼리가 끝날 때까지 기다릴 수 없습니다.
쿼리가 완료 될 때까지 nodejs가 기다리도록하려면 어떻게해야합니까? await / async를 잘못 사용하고 있습니까?
여기서 목표 d
는 쿼리가 완료된 후에 만 반환 하는 것입니다.
데이터베이스 파일
const DB_HOSTNAME = "localhost";
const DB_NAME = "testerino";
const DB_PORT = "8889";
const DB_USERNAME = "root";
const DB_PASSWORD = "root";
const mysql = require('mysql');
const con = mysql.createConnection({
host: DB_HOSTNAME,
user: DB_USERNAME,
password: DB_PASSWORD,
database: DB_NAME,
port: DB_PORT
});
con.connect(function(err) {
if (err) throw err
console.log("Connected to database");
});
async function query(sql){
var results = await con.query(sql);
console.log("foo completed")
return results
}
module.exports = {
con: con,
query: query
}
userLogin 파일
const db = require('../../common/database');
function attemptUserLogin(usernameOrEmail, password){
var d = {err: [], res: {}};
console.log("attemptUserLogin");
const foo = db.query("SELECT * FROM users");
console.log("This should wait for foo to complete");
return d;
}
module.exports = {
attemptUserLogin: attemptUserLogin
};
결과
Connected to database
attemptUserLogin
This should wait for foo to complete
foo completed
^ 그것은 기다리고 있지 않습니다
callback
와 함께 사용할 필요가 없습니다 await
. con.query()
함수가를 반환 하는지 확인하십시오 promise
.
async function query(sql){
var results = await con.query(sql); // the result will be stored in results variable ,once the promise is resolved
console.log(results) // the query result will be printed here
return results // the result will be wrapped in promise and returned
}
위의 함수는 약속이 해결되고 반환 된 데이터가 결과 변수에 저장 될 때만 결과를 반환합니다.
이제 위의 함수를 사용하여 데이터를 얻으려면 두 가지 방법으로 수행 할 수 있습니다.
1- 사용 then
.
query().then(data=>{
console.log(data) // this variable data holds the value you returned from above query function
})
2-await를 사용하여 함수 호출 (하지만 비동기 함수에서 수행해야 함)
async function other()
{
let query_result=await query(); // it will return the data from query function above
}
이 답변을 참조하십시오 . 데이터를 쿼리하는 모든 가능한 경우에 대해 논의했습니다.
편집-문제는 attemptUserLogin 함수에 있습니다. 비 동기화해야합니다.
async function attemptUserLogin(usernameOrEmail, password){
var d = {err: [], res: {}};
console.log("attemptUserLogin");
const foo = await db.query("SELECT * FROM users"); // use await here
console.log(foo);// result from query function above
return d;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다