我有一个函数,可以在完成一些工作后设置一个值。
function TheFunction(){
promise = new Promise(async (resolve, reject) => {
var success = false;
$query = 'SELECT * FROM `stuff`';
connection.query($query, await function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
console.log(err);
return;
}
console.log("Query succesfully executed", rows);
if (rows === undefined || rows.length == 0) {
console.log("no things exist in the database");
resolve(false);
}
else{
console.log("things are initialized");
success = true;
}
});
})
resolve(success);
}
之后,我将这个值捕获到一个返回承诺的变量中。我已经等待了我的函数,因为它需要一些时间来执行并返回正确的值。但是,TheFunction()和匿名函数都没有等待,并且b在现实中应该为true时返回false。
async function testfunction2()
{
var b = await TheFunction();
console.log(b);
if (b == true)
console.log("we did it!");
}
我尝试了不同的变体,例如.then()、. ConfigureAwait和不同的await变体,但到目前为止没有任何变化。我是JavaScript新手,请多加解释