gpt4 book ai didi

javascript - 仅当异步调用在循环内完成时输出

转载 作者:行者123 更新时间:2023-11-28 18:34:23 26 4
gpt4 key购买 nike

我正在使用 Google Places API 并尝试获取 placeTable 的值。当我尝试最后更新时,变量为空。

var placeTable;

function callback(results, status) {

if (status == google.maps.places.PlacesServiceStatus.OK) {

for (var i = 0; i < results.length; i++) {

var request = { placeId: results[i].place_id };

service.getDetails(request, callbacks);

placeTable = "<table>";

function callbacks(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
placeTable += "<tr><td>" + place.name + "</td><td>" + place.vicinity + "</td></tr>";
}
}
container.innerHTML += placeTable + "</table>";
}

}
}

更新:通过所有输入,我能够调整我的代码并计算响应。

function callback(results, status) {

if (status == google.maps.places.PlacesServiceStatus.OK) {

var j = 0;
var placeTable = "<table>";

for (var i = 0; i < results.length; i++) {

var request = { placeId: results[i].place_id };

service.getDetails(request, callbacks);

function callbacks(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {

j++;

placeTable += "<tr><td>" + place.name + "</td><td>" + place.vicinity + "</td></tr>";

if(results.length === j){

container.innerHTML += placeTable + "</table>";

}
}
}
}

}
}

最佳答案

回调可能会在将来的某个时候被调用。所以你的路线:

container.innerHTML += placeTable + "</table>";

在调用callbacks函数之前执行。

更新:重构代码:

function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
return;
}

var placeTable = "<table>";
var detailsDone = 0;

function callbacks(place, status) {
detailsDone += 1;

if (status == google.maps.places.PlacesServiceStatus.OK) {
placeTable += "<tr><td>" + place.name + "</td><td>" + place.vicinity + "</td></tr>";
}

if (detailsDone >= results.length) {
container.innerHTML += placeTable + "</table>";
}
}

for (var i = 0; i < results.length; i++) {
service.getDetails({
placeId: results[i].place_id
}, callbacks);
}
}

关于javascript - 仅当异步调用在循环内完成时输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37393129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com