Is it possible to pause code execution using async await?

As an experiment to understand async/await, I implemented the init function in a convoluted manner:

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 are structured like this:

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

I would like all functions in init to finish before rendering the view. However, the console shows 1,9,2,3,4,5,6,7,8. Is there a way to ensure that the code waits for the functions in init to complete?

Answer №1

To incorporate async/await into your code snippet, you can structure it like the following example:

 async function start() {
        console.log(1);
            await usersStore.getUsers();
            await productsStore.getProducts();
            await ordersStore.getOrders();
            await customersStore.getCustomers();
            await settingsStore.getSettings();
            await transactionsStore.getTransactions();
        console.log(9);
    }

Answer №2

Transform the init() function into an async function for better control over asynchronous operations. Now you can use await to wait for each function to finish.

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

If something in your code depends on the completion of the init() function, remember to await its execution. In this example, I'm utilizing an IIFE (Immediately Invoked Function Expression) but feel free to adapt it as needed.

(async () => {
    await init();

    // Continue with the rest of your code.
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to convert 'arr' into a function so that I can utilize 'arr.sort' without having to define an array beforehand?

I am looking to develop a custom function that can identify the smallest value in a given set of numbers without relying on the Math.min(); method. Check out the code I have come up with: function min(arr) { var lowest = arr.sort((x, y) => x - y); ...

The form does not allow for editing in the input fields

I am experiencing an issue with my simple form where I can only click and type into the input fields below the menu. The CSS and JS in this snippet may be a bit all over the place, but it closely resembles my app's structure. I'm baffled by why t ...

What is the process for initializing the JWPlayer when it is embedded within Sitefinity?

We utilize a Sitefinity portal and have integrated the jwplayer on a specific page. Upon inspecting the page's HTML code, I only see a DIV element with an ID assigned to the video player. There is no indication of the javascript code present. However, ...

Display a view with Vue Router based on specific conditions

Currently, I am working on a layout that includes optional sidebars based on the vue routes. Here is what I have so far: In my App.vue, I have a MainLayout component with slots where the router views are rendered. <main-layout> <template #m ...

Identifying Internet Explorer's tracking protection through feature detection in JavaScript

It seems that Soundcloud does not offer support for browsers older than IE11, possibly due to tracking protection in IE9 and IE10. Is there a simple method using javascript to detect if tracking protection is enabled? I want to filter out all users with ...

What is the best way to halt a specific function in jQuery?

I recently developed a website for my photographer friend, and I implemented a feature where the home page is initially blurred. Visitors can click a button to unblur the content. While the functionality works smoothly, there's one issue - every time ...

Is there a chance of a race condition occurring during file uploads when processed individually through AJAX with PHP?

I have created a form for uploading multiple files. <form id="myuploadform" enctype="multipart/form-data"> <input id="uploadedFiles" name="uploadedFiles" type="file" class="form-control&qu ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

Guide on transferring Javascript array to PHP script via AJAX?

I need to send a JavaScript array to a PHP file using an AJAX call. Here is the JavaScript array I am working with: var myArray = new Array("Saab","Volvo","BMW"); This JavaScript code will pass the array to the PHP file through an AJAX request and displ ...

When using a yarn linked package, vue-cli-service may not be able to serve

I have a npm package hosted on GitHub that is a Vue component. To build it, I use the command vue-cli-service build --target lib --name init-map src/main.ts. Below is the content of the main.ts file: import InitMap from "./components/InitMap.vue" ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Failure to respond to dual part form by RemoveClass

Currently, I am utilizing jQuery to visually control a form. The issue arises when trying to remove classes from the first part of the form using removeClass. While this works initially, upon clicking the button to advance to the second part of the form, t ...

Enhanced Button Dropdown Function

I have the following HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Expanding Dropdown Menu</tit ...

The function in JQuery that is being called using the onclick event is not functioning as anticipated on the PHP download

I have created a Php script that keeps track of the number of times a file is downloaded using Php and JQuery. The issue I am facing is that my function getStatus() calls the Php file every second, consuming a lot of bandwidth. I attempted to optimize by t ...

Manipulating the contents of a component's state by adding or removing objects

Currently, I am facing an issue with a list of check inputs where when they are selected and deselected, I am attempting to add or remove them from the state. However, I have noticed that when I deselect one item, the previously selected item is the one ...

Using $npm_package_ notation to retrieve information about the version of a private package

When using Npm, you can easily access package information from the package.json file by using a helpful prefix. For example, you can extract the react version with $npm_package_dependencies_react to find the current version of react listed in the file. Ho ...

Sign up for an observable only when a specific variable has been modified

I am facing an issue where I need to restrict the usage of rxjs's subscribe method to only certain property changes. I attempted to achieve this using distinctUntilChanged, but it seems like there is something missing in my implementation. The specif ...

transforming PDF into an Image using PhantomJS

Currently, I am using PhantomJs to convert webpages into images successfully. Here is the code snippet I am using: phantomjs.exe rasterize.js http://myurl.com/mypage/ out_put_image.png Even though this method works well for webpages, it encounters an iss ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...

What could be the issue with my injection supplier?

When running the following code, the configuration works fine, but an error is returned: Uncaught Error: [$injector:unpr] Unknown provider: AngularyticsConsoleHandlerProvider <- AngularyticsConsoleHandler <- Angularytics Code snippet: angular.modu ...