代码之家  ›  专栏  ›  技术社区  ›  Ivar

如何使用async wait使代码执行等待?

  •  -1
  • Ivar  · 技术社区  · 2 年前

    我有一个init函数,我用一种荒谬的方式编写它,只是为了检查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)
    }
    

    所有功能都采用以下形式:

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

    我想要的是在渲染视图之前完成所有功能,但控制台给了我1,9,2,3,4,5,6,7,8。有没有办法在代码继续之前等待init中的函数完成?

    2 回复  |  直到 2 年前
        1
  •  2
  •   MrXQ    2 年前

    您可以使用 async/await 在您的示例中,如下所示:

     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);
        }
    
        2
  •  1
  •   Jeet Gangwar    2 年前

    转换 init() 函数转换为 async 作用现在你可以了 await 以完成每个功能。

    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);
    }
    

    您还需要等待 init() 函数,如果某个东西依赖于它的执行。这里我使用IIFE,但你可以随心所欲。

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