Skip to content
Advertisement

Wait for one function to finish before continuing?

When running the following code tidied in functions or not, it still writes to my file incorrectly. One thing that did work was wrapping those functions inside of a setTimeout method, with the seconds somewhere around 10. I just didn’t like the idea of hardcoding those values and taking anymore time to complete than it should. What’s a better way of going about this? I need help understanding async/await a little more as you can tell but what better way than to fail and ask for help!

JavaScript

Advertisement

Answer

The issue is that making a function async doesn’t make it automatically wait for anything asynchronous going on inside it

async/await is syntax “sugar” for working with Promises, and Promises only

So, if you use the promise version of writeFile/readFile like so

JavaScript

you can write your code as follows

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement