When using async/await, your asynchronous code with begin executing, but its resolution will jump back into the synchronous code only when you use the await keyword. When you have multiple asynchronous functions, they will only execute sequentially when you have synchronous code running in between them because when you invoke the function is when the asynchronous portion of the code begins executing. In this case, the timer starts when you invoke the function, so you need to wait for the first timer to resolve before kicking off the second timer.
See this code snippet and check out the examples in this link to clarify.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
async function sequentialStart() {
console.log('==SEQUENTIAL START==')
// 1. Execution gets here almost instantly
const slow = await resolveAfter2Seconds()
console.log(slow) // 2. this runs 2 seconds after 1.
const fast = await resolveAfter1Second()
console.log(fast) // 3. this runs 3 seconds after 1.
}
The other issue is that when you declare your functions, you run them immediately and assign their values to variables. With minimum modification to your code, you need to set up your functions like below and only call them once you're ready to start the timer.
// a promise
let promise1 = function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved1');
}, 4000);
});
};
let promise2 = function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved2');
}, 4000);
});
};
// async function
async function asyncFunc() {
// wait until the promise resolves
let result1 = await promise1();
console.log(result1);
let result2 = await promise2();
console.log(result2);
}
// calling the async function
asyncFunc();