javascript - 为什么履行的诺言没有定义?
问题描述
你能给我解释一下吗?
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
if(true) {
resolve('succes')
} else {
reject('failure')
}
}, 4000)
})
promise1.then(result => console.log(result))
为什么在那之后我在控制台上获得了“成功”之类的东西
Promise {<fulfilled>: undefined}
如果我的承诺返回“成功”字符串值,为什么会有未定义?这是因为 setTimeout 嵌套?我该如何解决这个问题?
解决方案
通过进行以下调整:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
if(true) {
resolve('succes')
} else {
reject('failure')
}
}, 4000)
})
promise1.then(result => {
console.log(result);
return result;
})
您将在开发工具上同时拥有 log 和 promise 返回值;
为什么?
undefined
是隐式返回值回调( return;
)的结果,当函数没有显式返回任何内容时,js引擎会return
在函数体的末尾添加隐式语句。
推荐阅读
- c - 'scanf' 后值发生变化
- python - 有没有办法使用 Twitter API 创建和销毁静音词
- cucumber - 我无法成功运行黄瓜报告
- docker - Network usage data between every two pairs of docker containers
- excel - 有条件地粘贴值,利用相邻单元格
- php - 这个登录系统有多安全?(在 PHP 中使用 Cookie)
- javascript - 打字稿:'any []'类型的参数不可分配给'[]'类型的参数.ts(2345)
- c# - how to check whether items present in list box & how to check list box has duplicates? in csharp
- c - 省略类型定义结构的显式转换
- ios - Xcode not giving debug information on crash