Мне известны замыкания и обратные вызовы в JavaScript, но очевидно, что я не получаю их на интуитивном уровне.
У меня есть небольшое приложение, которое собирает данные из API, и я могу легко console.log
отвечать на каждый запрос, моя проблема в том, что я пытаюсь собрать данные и создать объект для сохранения вфайл, когда все запросы завершены.
Я получаю, что nodejs - это один поток выполнения, и он не блокируется, но я не могу понять, куда поместить обратные вызовы, когда все внутренние запросы завершены. Iможет console.log
построенный объект.Вы увидите, что мои console.log
строки находятся не в том месте и выполняются до первого ответа от внутреннего запроса.
Разбивка
- Извлечение данных о стране
- Зацикливание на countryResponse и использование каждого идентификатора страны для извлечения деталей
- Добавление каждой детали в массив
- Добавление массива к объекту после завершения всех запросов.
код
const limit = require("simple-rate-limiter");
let request = limit(require("request")).to(1).per(200);
let options = {
method: 'POST',
url: 'https://myendpoint/details',
headers: {
'cache-control': 'no-cache',
'Content-Type': 'application/json'
},
body: {
"token": "TOKEN",
"method": "countries"
},
json: true
};
global.package = {};
global.services = {};
let countryServices = [];
/*
Country fetch
*/
request(options, function (err, response, countryResponse) {
if (err) {}
package.countries = countryResponse;
countryResponse.forEach(function (entry) {
let innerOptions = {
method: 'POST',
url: 'https://myendpoint/details',
headers: {
'cache-control': 'no-cache',
'Content-Type': 'application/json'
},
body: {
"token": "TOKEN",
"method": "services"
},
json: true
};
//THIS LINE OMG
//let countryServices = [];
innerOptions.body.countryCode = entry.countryCode;
request(innerOptions, function (err, response, innerResponse) {
if (err) {}
countryServices.push(innerResponse);
console.log(" inner response " + entry.countryCode + ' : ' + JSON.stringify(innerResponse, null, ""));
});//END innerResponse
});//END countryResponse.forEach
services = countryServices;
console.log(JSON.stringify(package, null, ""));
console.log(JSON.stringify(countryServices, null, ""));
});//END orderResponse
countryResponse
[
{
"countryCode": 1,
"countryName": "Virgin Islands (U.S.)"
},
{
"countryCode": 7,
"countryName": "Russian Federation"
}
]
innerResponse
[
{
"Type": "1",
"id": 2
},
{
"Type": "2",
"id": 3
}
]