I am trying to make the second function to wait until the completion of the first. In the following example, I am not able to achieve it. When exploring about async/await, it was said that the order of execution would be sequential. However, this does not seem to be the case here.
function one() {
setTimeout(() => {
console.log('Hi')
}, 5000)
}
function two() {
setTimeout(() => {
console.log('Bye')
}, 2000)
}
async function doAll() {
await one();
await two();
}
async function demo() {
await doAll();
}
demo()
Output
Bye
Hi
In this example, since function two involves less time, 'Bye'
is printed before the 'Hi'
. But I am trying to make sure when the first function completes its execution, then it should go to the second.
That's because functions that you defined can't be await
ed in a sense that they do not return a promise, that can resolve. Instead they complete instantly/"resolve" instantly.
function one() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Hi')
resolve();
}, 5000)
})
}
function two() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Bye')
resolve();
}, 2000)
})
}
async function doAll() {
await one();
await two();
}
async function demo() {
await doAll();
}
demo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With