0

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

  • Are you running it in an async function? – Tanay May 03 '22 at 10:39
  • @Tanay I am not. I may be wrong, but as far as I'm aware, `localforage.getItem()` returns a `Promise` so I have to use `await` to retrieve its value. I tested it out without `await` and it gave me `Promise {}` – Carl Eric Doromal May 03 '22 at 10:44
  • I know `localforage.getItem()` returns a Promise and to use `await` you have to run the expression in an async function – Tanay May 03 '22 at 10:46
  • @BGPHiJACK According to them, "localForage uses aync storage". (https://github.com/localForage/localForage) – Carl Eric Doromal May 03 '22 at 10:48
  • @Tanay I'm currently referring to their docs (https://localforage.github.io/localForage/#data-api-getitem) and I can't see anything regarding the use of async function. Can you provide an example or reference so that I may get a better idea on what you are trying to convey? – Carl Eric Doromal May 03 '22 at 10:56
  • check my answer – Tanay May 03 '22 at 11:01

1 Answers1

0

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()
Tanay
  • 871
  • 1
  • 6
  • 12
  • That did the work. Thank you. It is quite confusing how answers on other related questions imply that you could just use `await` directly when working with localForage. Case in point: https://stackoverflow.com/a/47034912/19023238 – Carl Eric Doromal May 03 '22 at 11:09