1

In the code below when I call func I get back a promise that resolves after 3 seconds which resolves to another promise. The nested promise then resolves to the number 43 after an additional 3 seconds. My question is why the console.log returns res:43 after 6 seconds instead of unresolved promise after 3 seconds. I .then func2 but I never .then otherFunc

async function func(){
  const val = func2().then((other)=>{console.log("res:"+other)})
}

async function func2(){
  return new Promise(resolve => {
    setTimeout(()=>resolve(otherfunc()),3000)

  })
}
async function otherfunc(){
  return  new Promise(resolve => {
    setTimeout(()=>resolve(43),3000)

  })
}
javajunkie
  • 107
  • 2
  • 9
  • The question is not really clear, can you rephrase please? *"My question is why the console.log returns res:43 after 6 seconds instead of unresolved promise after 3 seconds"* – P.S. Oct 08 '18 at 19:35
  • 1
    also no need to use async if you're not using await – mfreitas Oct 08 '18 at 19:38
  • 1
    Because both func2 and otherFunc wait for 3 seconds: `3*2 = 6` – Kevin Jantzer Oct 08 '18 at 19:38
  • When do do `.then()` on a value which is `Promise.resolve(someOtherPromise)`, that one `.then()` will wait for both promises, the original and someOtherPromise. They are chained together. – jfriend00 Oct 08 '18 at 19:46
  • Yes, that's exactly [what "resolve" means](https://stackoverflow.com/a/29269515/1048572). You can't [fulfill a promise with a promise](https://stackoverflow.com/q/32168194/1048572) – Bergi Oct 08 '18 at 20:46
  • Thanks everyone I figured that was what was happening I just didn't realize that .then would wait for all promises in the chain to be resolved. – javajunkie Oct 17 '18 at 14:46

1 Answers1

0

you resolve func2 with another promise which is otherfunc(), so func2 happens to resolve after 3 seconds, which then calls otherfunc which also resolves after 3 seconds. The result you see at your console.log statement shows 43 because the .then() will wait for all promises to complete.

Flame
  • 6,663
  • 3
  • 33
  • 53