skip to Main Content

I have an init function wich 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?

2

Answers


  1. You can use async/await in your example like this:

     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(9);
        }
    
    Login or Signup to reply.
  2. 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.
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search