程式碼片段1
var prepayment_apply,prepayment_operational;
//
loadMain().then(loadBtn()).then(function () {
console.log(prepayment_operational); // undefined
return loadProgress();
});
// fun1
function loadMain() {
return $.ajax({
url:'...',
success:function (data) {
prepayment_apply = data.prepayment_apply;
}
})
}
// fun2
function loadBtn() {
return $.ajax({
url:'...',
success:function (data) {
prepayment_operational = data.prepayment_operational;
}
})
}
// fun3
$.ajax({
url:'...',
type:'get',
dataType:'json',
load_animation:true,
success:function (data) {
...
}
})
我將$.ajax封裝到函數函數中時,用promise寫法打出的prepayment_operational是undefined。
var prepayment_apply,prepayment_operational;
//
loadMain().then(function () {
$.ajax({
url: '...',
success: function (data) {
prepayment_operational = data.prepayment_operational;
}
})
}
)
.then(function () {
console.log(prepayment_operational); // '111'
return loadProgress();
});
當我直接把ajax寫在then就能得到我想要的值。並且當我把程式碼段1中的
loadMain().then(loadBtn()).then(function () {
console.log(prepayment_operational); // undefined
return loadProgress();
});
改成
loadMain().then(function () {return loadBtn()}).then(function () {
console.log(prepayment_operational); // undefined
return loadProgress();
});
程式碼段1也能正常console出prepayment_operational。
想請教下這是為什麼。
then
拿到的應該是函數,而不是其他的東西。 。 。loadMain().then(loadBtn)....
jQ裡本身有Promise的(在deferred模組裡),例如:
這種寫法就是傳統的,而:
這種就是用了jQ內建的Promise機制(
$.ajax
本身会返回Promise,可以挂.done()
或者.fail()
)。也可以用.promise()
動態回傳promise物件。具體參考jQ文檔的「延遲對象」吧。