Search code examples
javascriptvue.jspinia

How can I make code execution wait with async await?


I have an init function which I wrote in a ridiculous way just to examine async/await:

function init() {
    console.log(1)
    accountsStore.getAccounts().then(() => {
        categoriesStore.getCategories().then(() => {
            sheetItemStore.getSheetItems().then(() => {
                accountsStore.getTotal().then(() => {
                    sheetItemStore.getTotals().then(() => {
                        balanceStore.getGrandTotal().then(() => {
                            console.log(8)
                        })
                    })
                })
            })
        })
    })
    console.log(9)
}

All functions take the following shape:

async function getAccounts() {
    let response = await axios.get(route('accounts.index', {'id': baseStore.balance.id}))
    accounts.value = response.data
    console.log(2)
}

What I want is for all functions to have completed before I render the view but the console gives me 1,9,2,3,4,5,6,7,8. Is there a way to wait for the functions in init to complete before the code continues?


Solution

  • Convert the init() function into an async function. Now you can await for each function to complete.

    async function init() {
        console.log(1);
        await accountsStore.getAccounts();
        await categoriesStore.getCategories();
        await sheetItemStore.getSheetItems();
        await accountsStore.getTotal();
        await sheetItemStore.getTotals();
        await balanceStore.getGrandTotal();
        console.log(8);
        console.log(9);
    }
    

    You also need to await the init() function if something depends on its exection. Here I'm using an IIFE but you can do however you want.

    (async () => {
        await init();
    
        // Rest of your code.
    })();