我試圖做一些承諾鏈使用角度的執行$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