如何等待多个网络请求完成?

时间:2020-02-29 18:38:35

标签: javascript jquery json getjson

在使用返回的数据调用函数之前,我需要等待两个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获得响应

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

等待多个异步功能完成的最佳方法是使用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. */