这是我正在努力的代码:
$(document).ready(function () {
var dataSets = [];
getSensorIDs().done(function (result) {
var sensorIDs = jQuery.parseJSON(result);
$.each(sensorIDs, function (index, value) { //loop through each id
getDataBySensorID(value.id).done(function (res) {
var temperatureData = jQuery.parseJSON(res);
var dataPoints = [];
$.each(temperatureData, function (index, value) {
dataPoints.push({
x: index
, y: value.value
});
})
dataSets.push(buildDataset(dataPoints, 1));
alert("Pushed something.");
});
});
alert("Drawed something.");
drawChart(dataSets);
})
});
问题是:Drawed something
发生在Pushed something
之前,即使程序流不喜欢它。我以为我用problem
修复了ajax的.done()
(它的异步),但它看起来并非如此。什么是这个问题的正确解决方案?
答案 0 :(得分:1)
它完全正常工作,因为"推动了一些东西"代码位于 NESTED AJAX请求的done
回调中。这将是未来的某个时候。因此,JavaScript引擎继续处理剩余的代码,其中包括" Drawed something"在接下来的顶级AJAX请求中,这样就发生了。
在将来的某个时刻,AJAX调用将完成,done
回调将会触发,然后你会得到一些东西"。
// 1. When the document is ready...
$(document).ready(function () {
var dataSets = [];
// 2. Make the AJAX call, BUT DONE RUN .done YET!
getSensorIDs().done(function (result) {
var sensorIDs = jQuery.parseJSON(result);
// loop through each id
$.each(sensorIDs, function (index, value) {
// 3. As part of the first AJAX call, make a SECOND one
getDataBySensorID(value.id).done(function (res) {
var temperatureData = jQuery.parseJSON(res);
var dataPoints = [];
$.each(temperatureData, function (index, value) {
dataPoints.push({
x: index
, y: value.value
});
});
// 5. The nested call finishes last
dataSets.push(buildDataset(dataPoints, 1));
alert("Pushed something.");
});
});
// 4. This runs first because the first AJAX call is finishing
// before the nested one (above)
alert("Drawed something.");
drawChart(dataSets);
});
});