To understand async/await, I am trying to display a console message once settimeout runs and expires. How do I fix my code below? I have 5 settimeout function and each should display respective message once finished.
function t1(){
setTimeout(() => {
console.log("1")
}, 1000);
}
function t2(){
setTimeout(() => {
console.log("2")
}, 2000);
}
function t3(){
setTimeout(() => {
console.log("3")
}, 3000);
}
function t4(){
setTimeout(() => {
console.log("4")
}, 4000);
}
function t5(){
setTimeout(() => {
console.log("5")
}, 5000);
}
async function main(){
await t1();
console.log("1sec done");
await t2();
console.log("2sec done");
await t3();
console.log("3sec done");
await t4();
console.log("4sec done");
await t5();
console.log("Yay! I am all done");
}
main();
You should use Promises
function t1(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("1");
resolve();
}, 1000);
});
}
function t2(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("2");
resolve();
}, 1000);
});
}
function t3(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("3");
resolve();
}, 1000);
});
}
function t4(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("4");
resolve();
}, 1000);
});
}
function t5(){
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log("5");
resolve();
}, 1000);
});
}
async function main(){
await t1();
console.log("1sec done");
await t2();
console.log("2sec done");
await t3();
console.log("3sec done");
await t4();
console.log("4sec done");
await t5();
console.log("Yay! I am all done");
}
main();
You are doing two mistakes
await before a calling a function t1,t2,t3.... await should be used on Promises. 1000,2000,... to setTimeout(). You should create a function which returns a Promise which will be resolved after 1 secondawait before the promise returned by that function let afterOne = (num) => new Promise(res => {
setTimeout(()=>{
//log the number passed to function after 1000 ms
console.log(num);
//resolve the current promise so then next setTimeout could be set
res();
},1000)
})
async function main(){
/*This loop does same as
await afterOne(0);
await afterOne(1);
await afterOne(2)
await afterOne(3);
await afterOne(4);
*/
for(let i = 0;i<5;i++){
await afterOne(i)
}
}
main();
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