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();
You need to await
promises, not functions alone. When you await function ...
(without calling it), the function is evaluated as an expression and then discarded. Just call the functions:
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();
Or, for this example, don't use functions at all - just await the promises directly:
async function LogAll() {
console.log("One: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("One: Completed");
resolve();
}, 1000);
});
console.log("Two: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Two: Completed");
resolve();
}, 2000);
});
console.log("Three: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Three: Completed");
resolve();
}, 3000);
});
}
LogAll();
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