【发布时间】:2015-01-14 20:57:48
【问题描述】:
我无法理解 Promises/A+ 规范的含义...
https://promisesaplus.com/#point-23
如果你有一个 promise 并调用 .then 并带有一个参数,这是否意味着无论成功或失败都会调用单个参数?
我觉得它可以通过任何方式来解释这一点。我想我最关心的图书馆是Q。
【问题讨论】:
标签: javascript asynchronous promise q
我无法理解 Promises/A+ 规范的含义...
https://promisesaplus.com/#point-23
如果你有一个 promise 并调用 .then 并带有一个参数,这是否意味着无论成功或失败都会调用单个参数?
我觉得它可以通过任何方式来解释这一点。我想我最关心的图书馆是Q。
【问题讨论】:
标签: javascript asynchronous promise q
.then() 处理程序的第一个参数,无论它是否是唯一的参数,始终是已完成的处理程序,并且仅在履行承诺时才被调用。如果传递了或没有传递第二个参数,则不会对第一个参数进行不同的处理。
【讨论】:
所以对于任何不确定的人,我制作了一个测试脚本,你可以在你的节点 REPL 中运行它。确定的答案是不,它不会用错误的附件调用成功。
var Q = require('q');
//call with whether or not the promise will resolve
function aPromise (bool) {
var def = Q.defer();
if (!bool) {
def.reject("oooo0o0o00o0 rejected");
}
def.resolve('winner winner chicken dinner');
return def.promise
}
var whatGonnaBe = aPromise(false)
//The Example
whatGonnaBe
.then(function (response) {
console.log('1')
console.log(JSON.stringify(response) + '1');
})
.then(function (response) {
console.log('2')
console.log(JSON.stringify(response) + '2');
},
function (response) {
console.log('3')
console.log(JSON.stringify(response) + '3');
})
【讨论】:
不,第一个参数始终是“成功”或“已解决”的参数。第二个参数始终是失败参数,在将 Promise 链接在一起时可以省略它,并使用单个“失败”参数来处理所有失败。这段代码只是概念性的:
promise1.then(function() {
return promise2;
}).then(function() {
return promise3;
}).then(function() {
/* everything succeeded, move forward */
}, function() {
/* catch any failure by any of the promises */
});
【讨论】: