Can't quite understand how to do this in Promises, as I started learning about them today. What I am trying to do is that:
- Send a GET request and iterate until final page is reached (I can do this)
- Concatenate response elements to an array (an array of JSON objects, also done)
- For each element in this array, perform async operation such as image upload and database query (stuck here)
Here's what I have done so far:
Following function iterates over all pages.
function getAllCountries(requestURL, pageNr, countries) {
return Request({
'method': 'GET',
'uri': requestURL,
'json': true,
}).then((response) => {
if (!countries) {
countries = [];
}
countries = countries.concat(response.data);
const meta = response.meta;
if (pageNr < meta['pagination']['total_pages']) {
pageNr += 1;
let formattedLink = Format(BASE_URL, API_TOKEN, pageNr);
return getAllCountries(formattedLink, pageNr, countries);
}
return countries;
});
}
Here is where I am having trouble:
getAllCountries(formattedLink, pageNr)
.then((countries) => {
// will call handleCountry method for each country here
// how do I handle the callback to/from handleCountry here?
// that is wrong
// countries.map(handleCountry);
})
.then(() => {
console.log('Handled all countries');
return res.sendStatus(200);
})
.catch((error) => {
console.log(error);
return res.sendStatus(500);
});
Here is how handleCountry function is:
function handleCountry(country, callback) {
// do stuff here
if (!country["extra"]) {
app.models.Country.upsert(countryJson, callback);
} else {
// do async stuff here, image upload etc with Async.auto
Async.auto({
'uploadImage': (autoCallback) => {
uploadImage(autoCallback);
}
'updateOnDb': ['uploadImage', (results, autoCallback) => {
// do stuff
app.models.Country.upsert(countryJson, autoCallback);
}
}, callback);
}
}
What should I do here? The order of handling countries is not important, by the way.