为什么后续的链式承诺得到解决?

Why are consequent chained promises resolved?

我正在努力了解 Promises/A+,但我对几点感到困惑。考虑一下:

function foo() {
    console.log("In 'foo' function: --> which returns a Promise");
    return new Promise(function (resolve, reject) {
        resolve()
    });
}

var promise1 = foo();

var promise2 = promise1.then(function () {
    console.log("Promise 1 has been resolved --> onFulfilled() returns a value");
    return 1;
});

var promise3 = promise2.then(function () {
    console.log("Promise 2 has been resolved --> onFulfilled() is not returning anything from inFulfilled()");
});

var promise4 = promise3.then(function () {
    console.log("Promise 3 has been resolved");
});

/* Console:
In 'foo' function: --> which returns a Promise
Promise 1 has been resolved --> onFulfilled() returns a value
Promise 2 has been resolved --> onFulfilled() is not returning anything from inFulfilled()
Promise 3 has been resolved
*/

承诺处理程序(成功或错误处理程序)具有 return 值。每次 then 调用都会创建一个新的承诺。

如果一个值被 returned,那么承诺是自动解决的。如果另一个 promise 被 returned,那么 promise 将等到它被解决或拒绝,然后再继续 promise 链中的下一个 then 调用。

我认为这可以解释您所看到的行为。

您要查找的行为位于 promise/A+ 规范中的 #7 (https://github.com/promises-aplus/promises-spec#the-then-method)。

promise2 = promise1.then(onFulfilled, onRejected);

"If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x)."

我从这里得到的是,当第一个承诺是 failed/resolved 时,从它创建的任何承诺(包括新承诺 promise2)都是 failed/resolved。

例如: 当您在您的示例中解决 promise1 时,所有后续承诺也会解决。

我对您的代码做了一些小调整:

  • 将参数传递给 resolve(data) 例如resolve(1001)
  • .then检索并显示数据
  • 同样在.thenreturn链中的下一个Promise与return new Promise

这是修改后的示例:

var promise1 = new Promise(function (resolve, reject) {
    console.log("Creating Promise 1");
    resolve( 1001 );
} );

var promise2 = promise1.then(function (data1) {
    console.log("Promise 1 has been resolved --> ", data1);
    return new Promise(function (resolve, reject) {
        console.log("Creating Promise 2");
        resolve( 1002 );
    } );
} );

var promise3 = promise2.then(function (data2) {
    console.log("Promise 2 has been resolved --> ", data2);
    return new Promise(function (resolve, reject) {
        console.log("Creating Promise 3");
        resolve( 1003 );
    } );
} );

promise3.then(function (data3) {
    console.log("Promise 3 has been resolved --> ", data3);
} );