如何等待多个网络请求完成?
How to wait for multiple network request to complete?
我需要等待两次 api 调用完成,然后才能使用返回的数据调用函数。
url = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&accept-language=si&lat=" + lat + "&lon=" + lon;
url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&accept-language=si&lat=" + lat + "&lon=" + lon;
$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {
这里我需要在两个getjson之间添加settimeout或者间隔2000毫秒的时间间隔。
之后可以获得来自一个和第二个 json 响应的响应。
如果没有转移到第二个 json,则不可能从第一个 json
获得响应
感谢您的帮助。
等待多个异步函数完成的最佳方法是 Promise.all
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
以下是使用 fetch 编写网络调用的更现代方式的示例:
async function fetchMap([lat, lon]) {
const request = await fetch(
`https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&accept-language=si&lat=${lat}&lon=${lon}`
);
return await request.json();
}
async function getMapData(coordinates1, coordinates2, callback) {
const request1 = fetchMap(coordinates1)
const request2 = fetchMap(coordinates2)
const resolvedResponses = await Promise.all([request1, request2]);
callback(...resolvedResponses);
}
// This will get data for Tokyo and New York,
// and wait to call the passed-in function until both sets of JSON data are return.
getMapData([35.6850, 139.7514], [40.6943,-73.9249], console.log);
/* ^ instead of "console.log" put a reference to whichever function you want to call.
It could be an anonymous function such as the one shown in your question. */
我需要等待两次 api 调用完成,然后才能使用返回的数据调用函数。
url = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&accept-language=si&lat=" + lat + "&lon=" + lon;
url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&accept-language=si&lat=" + lat + "&lon=" + lon;
$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {
这里我需要在两个getjson之间添加settimeout或者间隔2000毫秒的时间间隔。 之后可以获得来自一个和第二个 json 响应的响应。 如果没有转移到第二个 json,则不可能从第一个 json
获得响应感谢您的帮助。
等待多个异步函数完成的最佳方法是 Promise.all
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
以下是使用 fetch 编写网络调用的更现代方式的示例:
async function fetchMap([lat, lon]) {
const request = await fetch(
`https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&accept-language=si&lat=${lat}&lon=${lon}`
);
return await request.json();
}
async function getMapData(coordinates1, coordinates2, callback) {
const request1 = fetchMap(coordinates1)
const request2 = fetchMap(coordinates2)
const resolvedResponses = await Promise.all([request1, request2]);
callback(...resolvedResponses);
}
// This will get data for Tokyo and New York,
// and wait to call the passed-in function until both sets of JSON data are return.
getMapData([35.6850, 139.7514], [40.6943,-73.9249], console.log);
/* ^ instead of "console.log" put a reference to whichever function you want to call.
It could be an anonymous function such as the one shown in your question. */