异步函数像同步一样工作
asynchronous function work like synchronous
我会尽量简单,当我想在函数 (SetLogs) 中执行异步查询时,我会在所有调用结束时在日志中看到我的 console.log('query 1 log')
,而不是看到他在 console.log('start log ');
和 console.log('return pool logs');
之间,我有 2 个部分:
我的主打
logs.SetLogs(pool, req, res).then(bResultLog=> {
console.log('return pool logs');
})
console.log("END")
return pool
设置日志函数:
static async SetLogs(pool, req, res) {
var now = new Date();
var endpoint = req.originalUrl.split("?")[0].replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
console.log('start log ');
pool.query(query, function(err, results) {
console.log('query 1 log ');
return true
});
console.log('fin log ');
}
这是我的日志:
start log
fin log
END
return pool logs
query 1 log
正如我上面所说,你缺少await
、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
async function SetLogs() {
var now = new Date();
console.log('start log');
var res = await queryTest();
console.log(res);
console.log('fin log');
}
function queryTest() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
}
SetLogs();
我会尽量简单,当我想在函数 (SetLogs) 中执行异步查询时,我会在所有调用结束时在日志中看到我的 console.log('query 1 log')
,而不是看到他在 console.log('start log ');
和 console.log('return pool logs');
之间,我有 2 个部分:
我的主打
logs.SetLogs(pool, req, res).then(bResultLog=> {
console.log('return pool logs');
})
console.log("END")
return pool
设置日志函数:
static async SetLogs(pool, req, res) {
var now = new Date();
var endpoint = req.originalUrl.split("?")[0].replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
console.log('start log ');
pool.query(query, function(err, results) {
console.log('query 1 log ');
return true
});
console.log('fin log ');
}
这是我的日志:
start log
fin log
END
return pool logs
query 1 log
正如我上面所说,你缺少await
、https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
async function SetLogs() {
var now = new Date();
console.log('start log');
var res = await queryTest();
console.log(res);
console.log('fin log');
}
function queryTest() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
}
SetLogs();