如何在两个getjson之间添加延迟

问题描述 投票:0回答:1

我需要在两个json延迟计时器之间添加。

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获得响应

感谢您的帮助。

javascript jquery json getjson
1个回答
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);
}

getMapData([35.6850, 139.7514], [40.6943,-73.9249], console.log);
© www.soinside.com 2019 - 2024. All rights reserved.