An elegant way to wait for one function to complete first is to use Promises with async/await function.
setTimeout
in order to demonstrate the situation where the
instructions would take some time to execute.await
for the first function to complete
before proceeding with the instructions.Example:
//1. Create a new function that returns a promise
function firstFunction() {
return new Promise((resolve, reject) => {
let y = 0
setTimeout(() => {
for(i=0; i<10; i++){
y++
}
console.log('loop completed')
resolve(y)
}, 2000)
})
}
//2. Create an async function
async function secondFunction() {
console.log('before promise call')
//3. Await for the first function to complete
let result = await firstFunction()
console.log('promise resolved: ' + result)
console.log('next step')
};
secondFunction()
_x000D_
Note:
You could simply resolve
the Promise
without any value like so resolve()
. In my example, I resolved
the Promise
with the value of y
that I can then use in the second function.