Javascript 在异步函数中使用两个wait
我试图从两个异步函数返回一个值。我正在尝试此线程中使用的方法。 然而,我总是得到一个未定义的值Javascript 在异步函数中使用两个wait,javascript,asynchronous,async-await,Javascript,Asynchronous,Async Await,我试图从两个异步函数返回一个值。我正在尝试此线程中使用的方法。 然而,我总是得到一个未定义的值 common.loggedInUserisAdmin().then((currentUser) => { console.log(currentUser); // This line is executed before values return from loggedInUserisAdmin function. }); // Here is my async functions
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)
}
我发现您的代码中存在以下问题:
- 您将
语法与承诺链接混淆了asyncwait
- 回调函数返回的值不是外部
方法的返回值loggedInUserisAdmin
- 也不确定在异步方法中拥有异步IIFE的目的是什么
loggedInUserisAdmin
方法可以简化如下所示:
async loggedInUserisAdmin() {
const currentUser = await this.getCurrentAccount();
const userData = await this.getUserDetailsByEmail(currentUser.userName);
return userData.admin;
}
确保调用此方法的代码有一个catch
块来捕获和处理此方法执行期间可能发生的任何错误