【发布时间】:2019-08-14 16:38:02
【问题描述】:
我第一次在 Javascript 中使用 async/await 函数。我无法让我的脚本等待 AJAX 响应,然后再继续读取/使用该响应。
我知道这里已经有很多关于 async/await 函数没有按预期等待的问题,但其他问题的答案似乎对我没有用。
基本上,我要做的是遍历图层名称数组(对于OpenLayers 地图)和forEach 图层名称我正在发送 AJAX 调用以检索记录(如果它存在) 来自 MySQL 数据库。然后我简单地显示结果,转到下一层名称,发送下一个 AJAX 调用,等等。
这是我的代码:
async function getCellLayers() {
layerNames = [];
map.getLayers().forEach(function(layer) {
if (layer.get('type') == "cell") {
if (layer.getZIndex() == 100) {
layerNames.push(layer.get('name'));
if (layerNames.length == 1) {
fullExtent = layer.getSource().getExtent();
} else {
ol.extent.extend(fullExtent, layer.getSource().getExtent());
}
}
}
});
return layerNames;
}
async function getRecord(cell_date) {
$.ajax({
url: 'rec/getRecord/'+cell_date,
type: 'get',
dataType: 'json',
success: await function(response){
console.log("getRecord response: "+JSON.stringify(response));
return response['data'];
}
});
}
async function testAsyncAwaitFunction() {
let layerNames = await getCellLayers();
layerNames.forEach(async function(layerName) {
cell_date = layerName.substring(3)+"_"+window['currentImage'].substring(17,25);
console.log(cell_date+":");
let cellRecord = await getRecord(cell_date);
console.log("Matches: "+cellRecord.length);
console.log("testAsyncAwaitFunction response: "+JSON.stringify(cellRecord));
});
}
我希望在控制台中看到类似的内容:
cell101_20190202:
getRecord response: {"data": [{"id":1,"record":"cell101_20190202","value":"0.8"}]}
Matches: 1
testAsyncAwaitFunction response: {"data": [{"id":1,"record":"cell101_20190202","value":"0.8"}]}
cell102_20190202:
getRecord response: {"data": [{"id":2,"record":"cell102_20190202","value":"0.7"}]}
Matches: 1
testAsyncAwaitFunction response: {"data": [{"id":2,"record":"cell102_20190202","value":"0.7"}]}
[ ... and so on ... ]
但我却得到了这个:
cell101_20190202:
cell102_20190202:
(...)
getRecord response: {"data": [{"id":1,"record":"cell101_20190202","value":"0.8"}]}
getRecord response: {"data": [{"id":2,"record":"cell102_20190202","value":"0.7"}]}
(...)
getRecord response: {"data": [{"id":14,"record":"cell202_20190202","value":"0.6"}]}
(200x) Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
getRecord response: {"data": [{"id":15,"record":"cell204_20190202","value":"0.5"}]}
(...)
我从未见过以testAsyncAwaitFunction response 为前缀的JSON.stringify 行,可能是因为尝试获取cellRecord 长度的console.log 命令之前的行由于AJAX 响应尚未到达而失败。
我怀疑以下行将是这里的关键:
let cellRecord = await getRecord(cell_date);
但我不知道为什么那个似乎没有“等待”,即使上面几行的另一行似乎工作得很好:
let layerNames = await getCellLayers();
非常感谢能更好地掌握使用 async/await 的人的帮助。我更习惯于 PHP 和 Python,并且很难将我的思维方式转变为异步思考。
【问题讨论】:
-
为什么要等待函数声明?
-
在使用
await调用它之前将所有函数更改为Promise。 -
感谢大家的所有回复 - 非常感谢您的帮助。
标签: javascript ajax async-await