Home > Software engineering >  What's the best way to retrieve items with localforage and store their values on a dictionary?
What's the best way to retrieve items with localforage and store their values on a dictionary?

Time:05-03

I want to retrieve values with localforage and store them in a dictionary.

I've been trying this:

localforage.setItem('foo', 'bar');
baz = {
    foo: await localforage.getItem('foo')
}
console.log(baz.foo);

but it keeps giving me Uncaught SyntaxError: Unexpected identifier (at test.js:3:13) marking localforage.getItem('foo') on Line 3

When I enter this on console, it works as expected and prints bar

CodePudding user response:

You should call the getItem in an async function to use await. Also, localforage.setItem returns a Promise, so you should use await to make it synchronous

async function doWork() {
   await localforage.setItem('foo', 'bar');
   baz = {
       foo: await localforage.getItem('foo')
   }
   console.log(baz.foo);
}
doWork()
  • Related