【问题标题】:How to wait for multiple network request to complete?如何等待多个网络请求完成?
【发布时间】:2020-02-29 18:38:35
【问题描述】:

在使用返回的数据调用函数之前,我需要等待两次 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之间添加2000毫秒的settimeout或interval。 之后可以从一个和第二个 json 响应中获得响应。 如果不传输第二个 json,则无法从第一个 json 获得响应

感谢您的帮助。

【问题讨论】:

  • 你最后的陈述含糊不清。

标签: javascript jquery json getjson


【解决方案1】:

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

【讨论】:

  • 你好,我已经检查过了。但我怎样才能从两个不同的链接获取数据。如果你可以检查我已经发送了两个不同的链接。在 url 我们有 zoom=15 和 zoom=18
  • @progy85 您可以复制fetchMap 函数,重命名它并更改URL。 (有帮助吗?)
猜你喜欢
  • 2016-10-04
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多