我正在使用API和天气信息,因此我希望网络等待API调用成功后才能继续,因此调用它的函数是异步的,在里面等待。尽管如此,它给了我未捕获的SyntaxError:等待仅在异步函数中有效。
async showAll() {
this.cities.forEach(function (c) {
await m.loadData(c).then(); // here is the await, as you see is inside an async function
console.log(m.data);
var head = document.createElement("h3");
head.innerHTML = "Tiempo en " + c + ":";
$("body").append(head);
});
}
async loadData(city) {
$.ajax({
dataType: "json",
url: this.url + city + "&units=metric&lang=es&APPID=" + this.apiKey,
method: 'GET',
success: function (e) {
m.data = e;
console.log(e);
console.log(m.data);
},
error: function (e) {
console.log(e.responseJSON.message);
}
});
}