在我的程序中,我需要进行GET调用,然后将返回的数据传递给另一个GET调用,然后返回结果。发生这种情况时,我希望程序等待数据返回。
现在我想出了类似的东西:
async function getPlaceTag(lat, lng) {
jQuery.get('https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + lat + '&lon=' + lng)
.done(function (data) {
jQuery.get('http://overpass-api.de/api/interpreter?data=[out:json];way(' + data.osm_id + ');out;')
.done(function (data2) {
console.log(data2);
});
});
}
然后我用它:
mymap.on('moveend', async function () {
let coords = myMarker.getLatLng();
console.log('call tag');
await getPlaceTag(coords.lat, coords.lng); // I want to wait here until it gets done
console.log('after call');
})
我得到:
call tag
after call
[GET data] <-- printed my data after ~1sec
我希望它获取数据并在打印“通话后”之前打印出来:
call tag
[GET data]
after call
答案 0 :(得分:2)
您需要return
或await
调用done
的结果,以使您的async
函数等待其完成。
使用.then
(而不是.done
)和非async
函数:
function getPlaceTag(lat, lng) {
return jQuery.get('https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + lat + '&lon=' + lng)
.then(function (data) {
return jQuery.get('http://overpass-api.de/api/interpreter?data=[out:json];way(' + data.osm_id + ');out;')
.then(function (data2) {
return data2;
});
});
}
通过async
和await
使用return
函数:
async function getPlaceTag(lat, lng) {
const data1 = await jQuery.get('https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + lat + '&lon=' + lng);
return jQuery.get('http://overpass-api.de/api/interpreter?data=[out:json];way(' + data1.osm_id + ');out;');
}
请注意,在这两种情况下,它均有效,因为jQuery已更新为使其Deferred
成为有效的承诺。
FWIW,我不会为此使用jQuery,而是使用标准的fetch
istead。我有一个实用程序功能:
async function fetchText(url, init) {
const response = await fetch(url, init);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
}
然后像这样使用它:
async function getPlaceTag(lat, lng) {
const data1 = await fetchText('https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + lat + '&lon=' + lng);
return fetchText('http://overpass-api.de/api/interpreter?data=[out:json];way(' + data1.osm_id + ');out;')
}
类似地,当我需要读取结果并将其解析为JSON等时,可以使用fetchJSON
。
我不只是因为the footgun in the fetch
API¹而直接使用fetch
:即使在发生HTTP错误(例如404或500)时,它也实现了自己的诺言,而不是拒绝它。
¹这是我贫乏的小博客上的帖子。