Code segment 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) { ... } })
When I encapsulate $.ajax into a function, the prepayment_operational typed using promise is 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(); });
When I write ajax directly in then, I can get the value I want. And when I put the
in snippet 1loadMain().then(loadBtn()).then(function () { console.log(prepayment_operational); // undefined return loadProgress(); });
changed to
loadMain().then(function () {return loadBtn()}).then(function () { console.log(prepayment_operational); // undefined return loadProgress(); });
Code segment 1 can also console out prepayment_operational normally.
I would like to ask why this is.
then
What you get should be a function, not anything else. . .loadMain().then(loadBtn)....
jQ itself has Promise (in the deferred module), such as:
This way of writing is traditional, and:
This uses jQ’s built-in Promise mechanism (
$.ajax
本身会返回Promise,可以挂.done()
或者.fail()
)。也可以用.promise()
Dynamicly returns the promise object.Please refer to the "Delayed Object" in the jQ documentation for details.