【发布时间】:2020-04-16 18:14:38
【问题描述】:
我有一些方块在页面上滑动,以链式承诺方式: https://jsfiddle.net/u4x0qwfo/3
代码是:
new Promise(function(resolve, reject) {
$("#shape").css({
top: 100
});
setTimeout(function() {
resolve();
}, 1000);
}).then(function() {
return new Promise(function(resolve, reject) {
$("#shape2").css({
top: 100
});
setTimeout(function() {
resolve();
}, 1000);
});
}).then(function() {
return new Promise(function(resolve, reject) {
$("#shape3").css({
top: 100
});
setTimeout(function() {
resolve();
}, 1000);
});
}).then(function() {
return new Promise(function(resolve, reject) {
$("#shape4").css({
top: 100
});
setTimeout(function() {
resolve();
}, 1000);
});
});
(代码在此处的 sn-p 内运行不佳:此处第一个方块最初已经向下滑动)。
所以要查看履行处理程序返回什么承诺,以及.then() 返回什么承诺,我有https://jsfiddle.net/u4x0qwfo/10/
代码是:
let foobar;
let lala = new Promise(function(resolve, reject) {
$("#shape").css({
// ...
}).then(function() {
foobar = new Promise(function(resolve, reject) {
// ...
return foobar;
});
lala.then(function() {
console.log("checking:", lala, foobar, lala === foobar);
return new Promise(function(resolve, reject) {
在调试控制台中,我们可以看到promise 是不同的。但是为什么它们必须不同呢?
其实在the docs of .then() return value里面,据说是:
[如果
.then()] 返回另一个待处理的promise 对象,then返回的promise 的解析/拒绝将在处理程序返回的promise 的解析/拒绝之后。此外,then返回的 promise 的值将与 handler 返回的 promise 的值相同。
这表明这两个 promise 是不同的(一个由履行处理程序返回,一个由 .then() 返回)。 (我在the ES6 specs 中找不到描述)。问题是为什么?他们不能是同一个承诺吗?
第二部分说:
此外,then 返回的 promise 的值将与 handler 返回的 promise 的值相同。
我最初认为它的意思是“那时返回的承诺将与处理程序返回的承诺相同”,但只是发现它实际上意味着:“then 返回的承诺的解析值将是与处理程序返回的承诺的解析值相同”。 (这是描述它的正确方式吗?)。
在 Google Chrome 中,两个 Promise 都将显示相同的解析值 123456:https://jsfiddle.net/u4x0qwfo/11/
【问题讨论】:
-
"他们不能是同一个承诺吗?" - 不,他们不能。
then()返回的一个需要在将来创建另一个的回调之前创建,甚至运行。如果有的话 - 承诺可能会拒绝。