在异步函数中使用两个等待



我正试图从两个异步函数返回一个值。我正在尝试这个线程中使用的方法。在异步函数之外使用等待

然而,我总是得到一个未定义的值。

common.loggedInUserisAdmin().then((currentUser) => {
console.log(currentUser); // This line is executed before values return from loggedInUserisAdmin function.
});
// Here is my async functions code.
async loggedInUserisAdmin() {
(async () => {
await 
this.getCurrentAccount().then().then((currentUser) => {
this.getUserDetailsByEmail(currentUser.userName).then((userData) => {
return userData.admin;
})
})
})();
},
async getCurrentAccount() {
return await msalApp.getAccount();
},
async getUserDetailsByEmail() {
const dataUrl = `$https://localhost:12345/User/GetUserDetails?emailAddress=${emailAddress}`
const errorMessage = 'Error getting current user'
return await authorisedFetch(dataUrl, errorMessage)
}

我在您的代码中看到以下问题:

  • 您混淆了async-await语法和promise链接
  • 回调函数返回的值不是外部loggedInUserisAdmin方法的返回值
  • 也不确定在异步方法中使用异步IIFE的目的是什么

您的loggedInUserisAdmin方法可以简化如下:

async loggedInUserisAdmin() {
const currentUser = await this.getCurrentAccount();
const userData = await this.getUserDetailsByEmail(currentUser.userName);
return userData.admin;
}

请确保调用此方法的代码有一个catch块来捕获和处理此方法执行过程中可能发生的任何错误。

查看代码后,很容易识别混合promise/async/await/then等时的错误。事实上,代码比你想象的更容易解决。在Promise.then((value(=>{}(必须保持链接函数,但使用wait将收到一个值作为结果,并且必须将结果存储在变量或常量中。await会按顺序打开代码,而不是在使用Promises时打开和打开链接函数。看看下面的固定代码:


async loggedInUserisAdmin() {
const currentUser = await this.getCurrentAccount();
const userData = await this.getUserDetailsByEmail(currentUser.userName)
return userData.admin
}

在幕后,节点编译器/解释器正在利用状态机和一些管理来发挥神奇的作用,以使我们的代码变得简单。让我们的生活更轻松。

最新更新