I’m learning about promises, setTimeout and async calls and have done a great job of confusing myself. I think I’m lacking some understanding around the callback and how setTimeout works. I’ve been looking at Mozilla documentation and the various Stackoverflow posts regarding these topics. I’m still having some trouble wrapping my head around why some of the functions I’ve created behave the way they do regarding the timeouts that are set.
Between wait0
and wait1
I don’t understand why the timeout for wait0
works properly and wait1
doesn’t adhere to it. With wait2
it is like wait1
except wrapped in an arrow function expression. Why does that make the timeout work properly? wait3
isn’t actually using the callback so that makes sense why the promise
and then
functions don’t do anything. But it stops wait4
from running. Is it blocking progression indefinitely or actually ending execution? For wait4
I’m also not passing a value into the callback like with wait0
but the timeout isn’t being adhered to.
function wait0() {
return new Promise((resolve, failure)=>{
setTimeout(resolve, 2000);
});
}
function wait1() {
return new Promise((resolve, failure)=>{
setTimeout(resolve('resolved ' + new Date().toGMTString()), 2000);
});
}
function wait2() {
return new Promise((resolve, failure)=>{
setTimeout(()=>{
resolve('resolved ' + new Date().toGMTString());
}, 2000);
});
}
function wait3() {
return new Promise((resolve, failure)=>{
setTimeout(()=>{}, 2000);
});
}
function wait4() {
return new Promise((resolve, failure)=>{
setTimeout(resolve(), 2000);
});
}
async function test() {
await wait0().then((result)=>console.log(result)); // Works as expected
console.log(new Date().toGMTString());
await wait1().then((result)=>console.log(result)); // Doesn't adhere to timeout
console.log(new Date().toGMTString());
await wait2().then((result)=>console.log(result)); // Works as expected
console.log(new Date().toGMTString());
await wait3().then((result)=>console.log(result)); // Never resolves
console.log(new Date().toGMTString());
await wait4().then((result)=>console.log(result)); // Doesn't adhere to timeout
console.log(new Date().toGMTString());
}
test();