我希望 promise 处理程序记录 promise p1
(不是值“A”),因为 console.log
是用 p1
调用的直接地。但是,它以某种方式记录了“A”。 promise p1
是如何自动解析为“A”而不被调用的?例如,console.log(p1)
并没有像预期的那样直接输出“A”。幕后发生了什么事吗?
var p1 = new Promise(function(resolve, reject) {
resolve("A");
});
var p2 = new Promise(function(resolve, reject) {
resolve(p1);
});
p2.then(function(v) {
console.log(v)
});
编辑:我明白调用
p1.then((v) => return v))
返回一个用值 v 实现的新 promise。除非我在这里严重遗漏了什么,否则第二个 promise 构造函数中的“p1”引用应该直接传递给 console.log,从而导致阻塞
var p2 = new Promise(function(resolve, reject) {
resolve(p1);
});
p2.then(function(v) {
console.log(v)
});
成为
console.log(p1).
因为 console.log 是直接用 p1 调用的,而不是 p1.then(...) 的结果,所以 p1 不应该像打印另一个程序那样解析为值“A”
var promise = new Promise(function(resolve, reject) {
resolve("B")
})
console.log(promise)
不会产生字符串“B”。
EDIT2:我误以为传递给执行程序的 resolve 参数是未实现函数的包装器,这让我很困惑。查看Why does the Promise constructor require a function that calls 'resolve' when complete, but 'then' does not - it returns a value instead?了解更多详情。
最佳答案
Promise.resolve(value)
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you don't know if a value is a promise or not, Promise.resolve(value) it instead and work with the return value as a promise.
p1
是 thenable,因此 return promise 紧随其后。
关于javascript - 将另一个 promise 传递给 promise 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46490724/