gpt4 book ai didi

javascript - 我如何知道最后一个异步函数何时在 "for key in ob"循环中返回结果?

转载 作者:行者123 更新时间:2023-11-30 15:46:49 26 4
gpt4 key购买 nike

我有以下代码来遍历对象:

var data = [];
var obj = {...
};

for (var key in obj) {
if (!obj[key]["something"]) {
geocoder.geocode({
'address': key
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {

data.push({...});

}
});

// if last item
$.post("...", data, ...);
}
}

现在我想发布通过运行循环中调用的所有异步函数检索到的所有数据。

最佳答案

因为 geocoder.geocode()(它是 Google Maps API 的一部分)既不返回 Promise 也不返回 Deferred ,您必须将请求封装在您自己的 Promise 中,然后使用 Promise.all():

var promises = [];

for (var key in obj) {
if (!obj[key]["something"]) {
promises.push(new Promise(function (resolveWith, rejectWith) {
geocoder.geocode({
'address': key
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
data.push(...);
resolveWith(results);
} else
rejectWith(results);
});
}));
}
}

Promise.all(promises).then(function (resultsArr) {
// at this point all requests have been fulfilled
$.post(...);
});

参见 MDN

关于javascript - 我如何知道最后一个异步函数何时在 "for key in ob"循环中返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942603/

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