How to wait for setTimeout to complete first
function a() {
setTimeout(() => {
console.log('should wait');
}, 5000);
}
async function b(c) {
console.log('hello');
await c();
}
b(a);
console.log('out');
Hello
should wait
out
How to wait for setTimeout to complete first
function a() {
setTimeout(() => {
console.log('should wait');
}, 5000);
}
async function b(c) {
console.log('hello');
await c();
}
b(a);
console.log('out');
Hello
should wait
out
setTimeout
does not return a Promise and await
only works with Promises.
Also, put the console.log("out")
inside the b
function for it to run after the a
function.
Check the code snippet below, it does what you were looking for.
function a() {
return new Promise((res, rej) => {
setTimeout(() => {
console.log('should wait');
res();
}, 5000);
})
}
async function b(c) {
console.log('hello');
await c();
console.log('out');
}
b(a);
A function must return a promise if you want example to work properly (await keywords "awaits" for returned promise to resolve): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
You example should look like:
function a() {
return new Promise(resolve => {
setTimeout(resolve, 5000);
});
}
async function b(c) {
console.log('hello');
await c();
console.log('should wait');
}
await b(a);
console.log('out');
Note that you can use await
keyword on function, because declaring function as async automatically makes it return a promise.