[英]Calling async function from within async function returns undefined
(請原諒我,如果標題與問題不准確,這個問題令人難以置信)我的應用程序要求我根據數據庫檢查請求中的值。 為此,我創建了一個異步函數來查詢數據庫:
async function checktoken(){
return prisma.$exists.invalidtoken({token: "testtoken"}).then(result => {
return(result)
})
}
我知道數據庫調用自己的作品:
prisma.$exists.invalidtoken({token: "testtoken"}).then(result => {
console.log(result) // returns true
})
在每個請求觸發的函數中,我嘗試調用 checktoken():
async function getUser(token){
var promise = await checktoken()
var result = promise
console.log(result) //undefined
};
修改函數以包含對數據庫的顯式調用,但只有在它之前定義了var promise = await checktoken()
時才有效:
async function getUser(token){
var promise = await checktoken() //When this is removed result1 is undefinded
await prisma.$exists.invalidtoken({token: "testtoken"}).then(result1 => {
console.log("inside db call: "+result1) // true
})
};
我想我對 async/await 有一個根本的誤解,但我不確定我到底錯過了什么。
編輯:我已經根據收到的建議更新了我的方法,但它仍然不起作用。 我開始認為我的 ORM 正在做一些奇怪的事情:
async function test(token) {
const status = await prisma.$exists.invalidtoken({ token: token });
console.log(status);
return status;
}
test("123") //logs false (as it should)
async function getUser(token){
var status = await test(token) //logs undefined
console.log(status) //logs undefined
};
異步函數需要等待。 如果您正在使用 promise.then() 技術,那么您想要做的是返回一個新的 Promise(),並在 .then 回調函數中解析承諾
function checktoken() {
return new Promise((resolve,reject) => {
prisma.$exists.invalidtoken({token: "testtoken"}).then(result => {
doSomeOtherStuff();
resolve(result);
});
});
}
在功能上與
async checktoken() {
await prisma.$exists.invalidtoken({token: "testtoken"});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.