lundi 25 mai 2020

Await in then object

I am trying to write logic in JS to stop function execution abruptly (without executing further) when in call sequence. Check below code. Why isn't stopping after second call?

function myprom (value) {
  return new Promise (function (resolve, reject) {
    resolve("I Promise " + value)
  })
}

function myfunc (value) {
  console.log("Starting in " + value)
}

function terminate() {
  setTimeout(() => console.log("Edning"), 1)
}

function dummy() {
  console.log("I am not supposed to print anything")
}

async function call() {
  await myprom("to end without showing next line")
    .then(result => {
      myfunc(1)                       // Call # 1
      console.log(result)             // Call # 2
      terminate()                     // Call # 3
      dummy(1)                        // Call # 4
      terminate()                     // Call # 5
    })
    .catch(err => {
      console.log(err)
    })
}

call()

Below is the actual output of my code.

Starting in 1
I Promise to end without showing next line
I am not supposed to print anything
Ending
Ending

What is expected is,

Starting in 1
I Promise to end without showing next line
Ending

In general. how to stop js execution abruptly inside .then object?




Aucun commentaire:

Enregistrer un commentaire