为什么Promise的resolve返回消息没有在控制台正常显示?
问题排查结果
问题出在console.log语句中多余的一元正号运算符:
你代码中的写法是console.log('this is in the then ', +message),其中message前的+会单独尝试将字符串类型的message转换为数值类型:
- 你
resolve传入的'Success'是纯字符串,无法被转换为合法数值,转换结果为NaN,这就是你输出里出现NaN的原因。
修正后代码
let p = new Promise((resolve, reject) => { let a = 1 + 1 if (a == 2) { resolve('Success') } else { reject('Failed') } }) p.then((message) => { // 移除message前多余的+号即可 console.log('this is in the then ', message) }).catch((message) => { // catch分支同理移除多余的+号 console.log('this is in the catch ', message) })
修正后运行代码,控制台会正常输出this is in the then Success。
内容的提问来源于stack exchange,提问作者suga sunshie
相关产品推荐
相关产品推荐

