为什么随之而来的链式承诺得到解决?

时间:2015-01-31 02:00:15

标签: javascript node.js promise bluebird

我正试图绕过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
*/
  • 必须通过调用resolve()显式解析Promise 1,否则执行将停止。为什么这样,使用Promises 2和3,执行认为这些已经解决(不需要resolve())并且进展到链中的下一个.then
  • 的' onFullfilled()'函数链接到promise2,不返回值。我在规范中找不到任何明确的reference在这种情况下应该发生什么。此方案是否被视为函数返回undefined?这是否使用了库的实际实现?

3 个答案:

答案 0 :(得分:3)

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

如果返回值,则自动解析承诺。如果返回另一个promise,那么promise将等到它被解析或被拒绝,然后继续下一个promise,然后在promise链中调用。

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

答案 1 :(得分:0)

您正在寻找的行为位于承诺/ A +规范中的#7(https://github.com/promises-aplus/promises-spec#the-then-method)。

promise2 = promise1.then(onFulfilled, onRejected);

“如果onFulfilled或onRejected返回值x,请运行Promise Resolution Procedure [[Resolve]](promise2,x)。”

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

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

答案 2 :(得分:0)

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

  • 将参数传递给resolve(data),例如resolve(1001)
  • .then中检索并显示数据
  • .then中也用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);
} );