我正试图绕过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
*/
答案 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);
} );