-1

我有一个调用外部 API 的异步函数。我在 API 变量中得到了结果,控制台日志记录产生了正确的结果。

function getSourceAndCountry(arr) {
  let source = ``;
  let country = ``;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] && arr[i][j + 1]) {
        let API = `https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=`;
        source = arr[i][j];
        API += `${source}`;
        country = arr[i][j + 1];
        API += `&country_code=${country}`;
        console.log(API);
      }
    }
  }
}

console.logging 调用后产生以下结果:getSourceAndCountry(sourceToCountry)

https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=csbs&country_code=US
https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=jhu&country_code=CA
https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=jhu&country_code=IN

我尝试像这样使用 async-await:

async function oneTypeMultipleCountries(agent) {...
let response = Promise.resolve(result);
      response.then((res) => {
        console.log(res);
      });

async function getSourceAndCountry(arr) {
  let source = ``;
  let country = ``;
  let response;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] && arr[i][j + 1]) {
        let API = `https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=`;
        source = arr[i][j];
        API += `${source}`;
        country = arr[i][j + 1];
        API += `&country_code=${country}`;
        response = await getJSON(API);

      }
    }
  }
   return response;
}

控制台在 Promise 中记录 res 值会产生最后一个已解决的 Promise。我在这里想念什么。我无法弄清楚。

4

1 回答 1

0

您可能希望函数返回这样的地图

const getSourceAndCountry = async (arr) => {
  const responses = {};
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] && arr[i][j + 1]) {
        const source = arr[i][j];
        const country = arr[i][j + 1];
        const API = `https://coronavirus-tracker-api.herokuapp.com/v2/locations?source=${source}&country_code=${country}`;
        responses[`${country}:${source}`] = await getJSON(API);
      }
    }
  }
  return response;
}
于 2020-04-12T18:28:01.420 回答