At work, I needed to implement a feature, and simplified, the logic was roughly as follows:
bills.getData = function (monthNow) {
//DONE Get data of monthNow.
//url = The url address is determined by monthNow
var url = "api/data.json";
//noinspection JSUnusedGlobalSymbols
$.ajax({
url: url,
dataType: "json",
type: "GET",
success: function (d) {
Data = d;
},
error: function (d) {
window.console.log("error");
}
});
return Data
};
data = bills.getData(monthNow);
However, during testing, I found that it was completely wrong.
After debugging, I discovered that the ajax
success
event was only triggered after bills.getData
had finished executing, returned Data
, and the subsequent assignment statement had also completed. This was clearly incorrect. Analyzing the reason: Because ajax
requests are asynchronous, the actual situation was that Data
was returned before the success
callback inside bills.getData()
had even finished executing. This led to the final assignment statement being incorrect; it was not assigned the successful result of the ajax
request. This did not meet our expectations.
Therefore, the code structure needed to be changed. We needed to ensure that the assignment statement was executed only after the ajax
request had successfully completed.
There are two ways to achieve this effect: callback
and promise
.
For convenience, I chose the callback
approach here. The code then looked like this:
// Data is a global variable
bills.getData = function (monthNow, callback) {
//DONE Get data of monthNow.
//url = The url address is determined by monthNow
var url = "api/data.json";
//noinspection JSUnusedGlobalSymbols
$.ajax({
url: url,
dataType: "json",
type: "GET",
success: function (d) {
Data = d;
if (typeof callback === 'function') {
callback();
}
},
error: function (d) {
window.console.log("error");
}
});
};
bills.getData(monthNow,doSomeThing);
function doSomeThing(){
//doSomeThing with Data
}
This way, we can ensure that the data
within the callback
is the result of a successful ajax
request.
This article was published on July 5, 2015 and last updated on July 5, 2015, 3746 days ago. The content may be outdated.