У меня есть асинхронная функция, которая вызывает внешний 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)
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
Я пытался использовать asyn c -aaait так:
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; }
Консоль, записывающая значение res в обещаниях, создает последнее разрешенное обещание. Что мне здесь не хватает. Я не могу понять.
Вы можете захотеть, чтобы функция возвращала карту, подобную этой
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; }