I have the following code:
Promise .resolve('333') .then(()=>{setTimeout(()=>{Promise.resolve('123');},10000)}) .then(()=>{console.log("should wait");});
I thought that the output should be first ‘123’ and then ‘should wait’. From unclear reason the ‘should wait’ is printed first. I thought that the second then won’t start until the asynchrony function (setTimeout) won’t finished. I read that this is all the “magic” of using Promise and then. Now i’m very confused. Why for example it doesn’t happen when we call fetch function? fetch function is also asynchrony, so why the then after the fetch doesn’t start before the fetch ends?
Advertisement
Answer
Unless a .then
callback explicitly returns a Promise, the next .then
in the chain is guaranteed to run nearly instantly afterwards (it gets put into the microtask queue).
Right now, you’re not returning anything, so undefined
gets returned, so the second .then
runs immediately.
If you want the first .then
to cause the second to wait until the timeout finishes, return a Promise that resolves when the timeout resolves:
Promise.resolve('333') .then(() => { return new Promise((res) => { setTimeout(() => { res('123'); }, 3000); }); }) .then(() => { console.log("should wait 3 seconds"); });