1

I am trying to return a value from two async functions. I am trying the method used in this thread. Using await outside of an async function

However, I am always getting an undefined value.

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)
}
Pankaj
  • 2,618
  • 3
  • 25
  • 47

2 Answers2

1

I see following problems in your code:

  • You have mixed up async-await syntax with promise chaining.
  • Value returned from a callback function isn't the return value of the outer loggedInUserisAdmin method.
  • Also not sure what is the purpose of having an async IIFE inside an async method.

Your loggedInUserisAdmin method can be simplified as shown below:

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

  return userData.admin;
}

Make sure that code that calls this method has a catch block to catch and handle any errors that might occur during the execution of this method.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

After looking your code, it was easy identifying mistakes on mixing promises/async/await/then etc. In fact, the code is easier to solve than you think. In Promise.then((value) => {} ) you must keep chaining functions , but with await you will receive a value as result, and you have to store the result in a variable or constant. await turns your code sequential, instead of chaining functions on and on when using Promises. Take a look at the fixed code below:


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

Behind the scenes, node compiler/interpreter is doing magic with state machines and several management in order to turn possible our code be simple. Making our lives easier.

Jone Polvora
  • 2,184
  • 1
  • 22
  • 33