我有一个调用外部 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。我在这里想念什么。我无法弄清楚。