Wednesday, 7 June 2017

Why do you have to call return resolve() to properly resolve a Promise inside a then clause

When executing the following code it still logs why is this executed after resolve

function myfunction () {
  return new Promise((resolve, reject) => {
    resolve(21)
  })
}

function getscore () {
  return new Promise((resolve, reject) => {
    myfunction().then((result) => {
      console.log('before resolve')
      resolve(result)
      console.log('why is this executed after resolve')
    })
  })
}

(async function () {
  try {
    console.log(`result was ${await getscore()}`)
  } catch (err) {
    console.log(`error ${err}`)
  }
})()

The log output is:

before resolve
why is this executed after resolve
result was 21

Only when using return resolve(result) the execution of the Promise is properly finished. Why is that the case?



via Hedge

No comments:

Post a Comment