0

this function should return "HomeStack"

const getSessionPrevious = async () => {
try {
    const value = await AsyncStorage.getItem("token"); //value default is "#$#"%2356"
    if (value !== null) {
    return "HomeStack";
    } else {
    return "LoginStack";
    }
 } catch (error) {
    return "LoginStack";
 }
};

console.log(getSessionPrevious() ); //I need get the value of the function in this line
.
.
.
rest of my code

when I do:

console.log(getSessionPrevious );

returns:

      Promise {
        "_40": 0,
        "_55": null,
        "_65": 0,
        "_72": null,
      }

how can get the result of this promise?

yavg
  • 2,761
  • 7
  • 45
  • 115

2 Answers2

1

First, you need to add parenthesis to actually call the function. Then you need to call the function using await to actually wait for the return value. Since you can only use await in an async function, declare one for that purpose.

async function Demo()
{
    console.log(await getSessionPrevious()); 
}

Demo();

// Code here will be executed before Demo() is actually executed because we are not awaiting it.

Note that adding asynchronous code (like async/await or using plain promises) is contagious. If you want to work with the results, you have to support the async nature of the call all up the callstack. This is very well explained in these topics:

NineBerry
  • 26,306
  • 3
  • 62
  • 93
0

As it seems that you are trying to get an asynchronous value from the top-level, you have to use then, catch:

getSessionPrevious().then(value => {
  console.log("Previous session", value);
}).catch(error => {
  console.log("Error getting previous session", error);
});

Or you can also use an encapsulated anonymous asynchronous function:

(async () => {
  try {
    const value = await getSessionPrevious();
    console.log("Previous session", value);
  } catch (error) {
    console.log("Error getting previous session", error);
  }
})();
Javier Brea
  • 1,345
  • 12
  • 16