When I run an example that I found on the internet which uses setTimeout, it works fine. But when I replace setTimeout with a long running for loop the output appears after delay. Do we have to use a factory made asynchronous function all the time?
Original code:
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000)})
}
const doSomething = async () => {
console.log(await doSomethingAsync())
}
console.log('Before')
doSomething()
console.log('After')
Code with custom delay:
const doSomethingAsync = () => {
return new Promise(resolve => {
for(let i=0;i<4000000000;i++){}
resolve("I did something!");
})
}
const doSomething = async () => {
console.log(await doSomethingAsync())
}
console.log('Before')
doSomething()
console.log('After')
When the custom code runs the output of After happens after the delay, whereas in the original code After appears immediately.
Edit: By the way the question at Why isn't Javascript async function immediately returning? is similar but the order doesn't change in my case, timing does.