javascript - 将另一个 promise 传递给 promise 处理程序

标签 javascript promise es6-promise

我希望 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?了解更多详情。

最佳答案

来自MDN documentation :

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/

相关文章:

javascript - AngularJS 中 $interval 返回的 Promise 的参数是什么?

javascript - 链式 promise - 返回的 promise 解析不会导致调用 then 方法

javascript - 如何隔离 javascript 依赖关系

javascript - 退出时清除剪贴板

javascript - 何时使用 React 错误边界组件?

Node.js 打破 promise 链

javascript - 使用 Node 中的 Q promise 库在值数组上顺序调用/执行相同的函数;并返回一个包含结果的新数组/集合

javascript - 如何使用多个 XMLHttpRequest.responseText 值?

javascript - 为什么我们在 promise 链中使用 return,即使我们已经在函数中有 return?

javascript - 我如何保存我的小注册页面中的所有数据并显示它们