我正在深入阅读javascript承诺。我的理解遇到了一个根本问题。
这是一段代码:
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
resolve(console.log("a was true"));
} else reject("a was false")
})
为什么上面的代码会立即记录a was true
,即使我还没有这样调用它:
p.then((msg) => {
return msg
})
但是,下面的代码只记录.then()
调用的值
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
resolve("a was true")
} else reject("a was false")
})
p.then((msg) => {
console.log(msg)
}).catch((msg) => {
console.log(msg)
})
如果有人能指出,为什么第一段代码不需要.then()
链,而是做早期日志?
请注意,我知道这不是异步代码,它只是用于演示目的。
即使您没有.then
promise,promise执行器也会立即执行。
你的第一个代码相当于
let p = new Promise(function (resolve, reject) {
let a = true
if (a) {
let value = console.log('a was true');
resolve(value);
} else reject('a was false')
})
正如您所知,console.log()
将字符串作为副作用进行日志记录,并返回undefined
,因此该promise的解析值为undefined
。
在第二个示例中,promise的解析值是字符串"a was true"
,没有任何副作用被记录。