首页 > 解决方案 > 在 then 对象中等待

问题描述

我正在尝试在 JS 中编写逻辑以在调用序列中突然停止函数执行(而不进一步执行)。检查下面的代码。为什么在第二次通话后不停止?

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()

下面是我的代码的实际输出。

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

预期的是,

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

一般来说。如何在 .then 对象内突然停止 js 执行?

标签: javascripthtmlnode.jsweb

解决方案


您可以使用 return 而不是调用终止。那将解决您的目的。


推荐阅读