Frontend Development

How to wait for something to finish before doing something else in JavaScript.

In JavaScript, you may come into places where you need to wait until something is finished before continuing to do something else. In fact, this will probably happen often.

In an app I'm working on now, this happened to me. I'm working on a web application for an inventory program that will help a nursery track their plant inventory. It will make it easy for the customer to update their plant inventory, sizes and other details as the plants grow in the nursery.

I have a Vue Component that among other things, tracks the "nextSize" data of a plant. This is for a button that users can click to update the plant's size quickly and efficiently as plants grow larger. When a user clicks this button, I need to update the plant size in the data to be the next size, then send an axios patch request to the server with the updated plant information.

When I first built out the functionality, I simply wrote a method called assignNextSize. This is what it looked like:

 assignNextSize() {
        this.size = this.nextSize;
        this.updateSize(); //Another method that does the axios patch request.

What happened next was not what I wanted at all.

The patch request was sent before the size was updated! It didn't make sense to me since JS is supposed to be synchronous, but in this context the second call was completing because the assignment was not only what was happening. A vue watch property was then doing the update to the data id attribute, which was happening asynchronously. This was causing the assignment to finish, then send the request, but the data property was not yet updated.

In order to fix this, I simply created a Promise that would ensure the assignment and watch method was finished before the method call and patch request.

 assignNextSize() {
      new Promise((resolve, reject) => {
        this.size= this.nextSize; /// watch property on size updates data.size_id to be new id
        resolve(); // once finished resolve promise
        .then(() => {

After that, things worked as expected! If you ever need to make sure something is finished before doing something else, a Promise is a great way to go about it.

Chris Wray website logo

Trying to do my part in making the world a better place.

This site is hosted for free, so I am thanking the services I am using by adding a link to their websites here in the footer.

© 2020 Chris Wray. All rights reserved.