javascriptcookieses6-promisecookiestore

Convert value from promise to string (cookieStore.get question)


I'm attempting to fetch a part of a value from a cookie on a website. So I've written code to get the cookie value, that works fine. And I attempted to do a JSON.stringify() of the returned value into a string, but instead it converts it into an empty object. I suspect this is because the returned object is a Promise object but I don't know why that would make a difference. Here is what I've done so far.

const getCookie = async (name) => {
  const cookie = await cookieStore.get(name);
  if(cookie) {return cookie.value}
  else {console.log('cookie not found')}
}
const cookievalue = getCookie('foo');

And this returns:

PromiseĀ {<fulfilled>: 'locale%3Des_us'}

Which is in fact the cookie value that I want. But if I then run:

const newcookievalue = JSON.stringify(cookievalue);

I get:

'[object Promise]'

What I'm trying to do, by the way, is to run an IF statement on that value--if it's "es_us" do one thing, if it's "en_us" do another thing. So for right now the IF statement in place on getCookie is really just testing in the console that I can get and convert the value to a string, before I put the code in my application.


Solution

  • To get a value form an async function you should use await keyword. like this:

     const cookievalue = await getCookie('foo');