Not sure if this is a typo but you forgot to call resolve
so the next line after the await
will execute:
function setTimeoutSync(fn, milli) {
return new Promise((resolve) => {
setTimeout(() => {
fn()
resolve()
}, milli);
});
}
async function run() {
console.log('start');
await setTimeoutSync(() => {
console.log('setTimeoutSync');
}, 3000);
console.log('end');
}
run();
As for your question:
Can you explain how not calling resolve can result in the rest of the
function not executing?...
Well async await uses generators and promise behavior:
The purpose of async/await functions is to simplify the behavior of
using promises synchronously and to perform some behavior on a group
of Promises. Just as Promises are similar to structured callbacks,
async/await is similar to combining generators and promises.
A generator can yield results thus not terminating the execution context, and can continue it where it left off.
Basically your example could be written with Promise.prototype.then() callback:
function setTimeoutSync(fn, milli) {
return new Promise((resolve) => {
setTimeout(() => {
fn()
resolve()
}, milli);
});
}
async function run() {
console.log('start');
setTimeoutSync(() => {
console.log('setTimeoutSync');
}, 3000)
.then((result) => {
console.log('end');
});
}
run();
So as you see, if we are not resolving, the callback to .then
won't run.