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
You can use
async/await
in your example like this:Convert the
init()
function into anasync
function. Now you canawait
for each function to complete.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.