I would just like to understand how promises and await work together. Look at the following code:
console.log("One: Started");
setTimeout(function(){console.log("One: Completed")}, 1000);
console.log("Two: Started");
setTimeout(function(){console.log("Two: Completed")}, 2000);
console.log("Three: Started");
setTimeout(function(){console.log("Three: Completed")}, 3000);
So this of course logs:
One: Started
Two: Started
Three: Started
One: Completed
Two: Completed
Three: Completed
I would like to have the one complete before the next one starts. I wrote this with my understanding of promises and await but this is not working. Would someone please try and edit this code to get it working. And please and an explanation as I am trying to understand promises and await
async function LogAll() {
console.log("One: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("One: Completed");
resolve();
}, 1000);
});
}
console.log("Two: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("Two: Completed");
resolve();
}, 2000);
});
}
console.log("Three: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("Three: Completed");
resolve();
}, 3000);
});
}
}
LogAll();