Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i make code execution wait with async await?

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 funcions 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading