【发布时间】:2020-09-12 19:05:06
【问题描述】:
我正在尝试在 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 执行?
【问题讨论】:
-
运行您的代码是个好主意:我漂亮确定这不是输出,因为您的代码中有一个类型为“Edning”;) (这不是修复该类型的提示,而是提示再次实际运行您的代码,以查看您在帖子中发布的内容是否仍然符合您的想法)
-
话虽如此:为什么你期望你说你期望什么?您编写的代码中没有任何内容可以缩短
myprom.then...代码的执行时间,那么您为什么认为它不应该运行您的其余代码呢? -
一种方法是
throw一个错误,它会触发catch() -
.then(myFunc).then(terminate).then(dummy)不会在terminate拒绝时调用dummy
标签: javascript html node.js web