javascript - 在 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 执行?
解决方案
您可以使用 return 而不是调用终止。那将解决您的目的。
推荐阅读
- reactjs - 材质的 UI 默认文本字段颜色是什么颜色?
- python - Tkinter 按钮函数调用后使用全局变量触发 If-Else 条件
- sql - What's causing "Incorrect syntax near the keyword 'AS'"
- javascript - 如何停止获取缩短 URL API 的数据,因为它不断添加具有多个不同缩短版本的相同获取的链接数据
- security - 想知道可以利用 WebSphere Application Server Network Deployment 的漏洞是否也利用 WebSphere Application Server?
- android - 在android(kotlin)中转换pdf文件的二进制内容
- c# - 如何将属性(特定于应用程序的数据)添加到 Twilio SMS - 2021
- python - Instagram 的 InstaPy BOT/如何运行多个脚本
- python - 使用python Wget lib时下载错误
- apache-spark - 将 1 到 n 个项目连接到新的 spark 列中