javascriptasynchronousasync-awaitlocal-storagelocalforage

LocalForage async/await getItem() wait for 2 variables and then finish loading


I'm new to the Javascript async calls and understanding promises. I'm so used to Do This, Wait for This.

I am using localforage in my site, and I need to get data from 2 sources.

var ordersRaw = null
var itemsRaw = null
localforage.getItem('ordersRaw').then((res) => {
    if(res) {
        ordersRaw = res
    } 
})
localforage.getItem('itemsRaw').then((res) => {
    if(res) {
        itemsRaw = res
    } 
})
if(ordersRaw && itemsRaw) {
    // now load the screen
} else { console.log('NO DATA') }

After I have these 2 pieces of data, finish loading the screen by running a function

displayWithResults()

But if I run it like this, it will instantly fail, because of the async functionality. and cause NO DATA to show up.

I consistently run into this issue with javascript and I can't seem to fully wrap my head around it accurately. Any help here is appreciated.


Solution

  • There are a few ways to solve this:

    It comes down to the fact that you want to retrieve all results asynchronously before performing the check.

    I suggest that you use async await, it's just clean.

    The code would look something like this:

    (async() => {
        try {
            const ordersRaw = await localforage.getItem('ordersRaw');
            const itemsRaw = await localforage.getItem('itemsRaw');
            if(ordersRaw && itemsRaw) {
                // now load the screen
            } else { 
               console.log('NO DATA') }
            }
        } catch (e) {
            console.log(e);
        }
    })();
    

    Edit: Above code executes sequentially. Please replace with something like:

    const getOrders = localforage.getItem('ordersRaw');
    const getItems = localforage.getItem('itemsRaw');
    const [ordersRaw, itemsRaw] = await Promise.all([getorders, getItems]);