2

Why do I have to wrap await with () in order to get the output I need. I am hoping to get only the uid from the object

The data that is return from the function that I am importing is exactly how you see it

{uid : 'abcdefg', email:'[email protected]'}
import {ActiveUser} from './teamMembers.service';

export const retrieveList = async date => {
console.log('active user information here', (await ActiveUser()).uid); 
// outputs: Works as expected
// active user information here abcdefg

console.log('active user information here', await ActiveUser().uid); 
// outputs: 
//Undefined

console.log('active user information here', typeof (await ActiveUser()));
// outputs: 
// object
}
2
  • Because ActiveUser would be returning a promise so u need await to wait till it executes and returns your Object. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . await keyword is used for the function call, hence you need the braces and then you access the key of the object. Commented Oct 30, 2021 at 13:06
  • 1
    Because the object property access "dot" operator has a higher precedence so it gets evaluated first. Without the explicit grouping it reads as await (ActiveUser().uid). Remember PleaseExcuseMyDearAuntSally? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 30, 2021 at 13:09

1 Answer 1

3

The await operator is used to wait for a Promise (The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value) and it can only be used inside an async function.

You need to await you're async task (ActiveUser) once and after that you can just reference it's data (which is the resolved state of that async code happening there)

import {ActiveUser} from './teamMembers.service';

export const retrieveList = async date => {
   const data = await ActiveUser();
   const uid = data.uid;
   const name = data.name;
}

I suggest you read more The event loop and the concurrency model and it's secret behind the JavaScript's asynchronous programming.

More about async - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

More about event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.