我试图做一些承诺链使用角度的执行$q
,但似乎已经遇到了几乎被迫进入金字塔的厄运局面的路障。
我宁愿做:
function doYetAnotherAsync() {
return $q(function(resolve, reject){
var transaction = {
cvc: vm.cvc,
exp_year: vm.expirationYear,
exp_month: vm.expirationMonth,
number: vm.cardNumber
}
Stripe.card.createToken(transaction, function(responseCode, response) {
console.log('createToken');
if(responseCode === 200) {
resolve({
id: core.get(response, 'id'),
cardId: core.get(response, 'card.id')
});
}
reject(response);
});
});
}
function doAnotherAsync() {
return $q(function(resolve, reject){
var globalVar;
doSomeNormalAjaxCall()
.then(function(response){
globalVar = response.id;
return doYetAnotherAsync()
})
.then(function(stripeData){
console.log('stripeData', stripeData);
// stripeData returns a $$state object
return finalAsync()
})
.then(function(response){
// handle final data here
// resolve/reject $q
})
})
}
doSomeAsync()
.then(doAnotherAsync)
请注意,在doAnotherAsync()
,我很想能够使用这种形式:
someAsync()
.then(function(){
return someOtherAsync()
})
.then(function(){
return yetAnotherAsync()
})
.then(function(){
// finally do some stuff
})
为了避免金字塔的-厄运。
但是,在上面的代码中,第二个.then()
解决得很早,一个$$state
对象沿着链传递,而不是正常对象{id: '', cardId: ''}
。
的console.log
命令举例:
stripeData d {$$state: Object}
XHR finished loading: POST "https://api.stripe.com/v1/tokens"
createToken
要保留链接的承诺订单和获得真正的对象的反应,我不得不做的事:
function doAnotherAsync() {
return $q(function(resolve, reject){
var globalVar;
doSomeNormalAjaxCall
.then(function(response){
globalVar = response.id;
return doYetAnotherAsync()
.then(function(stripeData){
// some logic
return finalyAsync()
})
})
.then(function(response){
// final processing
})
})
}
缺少什么我在这里?
它绝对可以解决。 'globalVar'的作用是什么? “doSomeNormalAjaxCall”究竟是什么,它是jQuery吗?从它返回的承诺有问题。一个承诺不能将不确定的承诺传递给下一代(“尽早解决”),$ q和本地承诺是合规的,不会这样做。 – estus