I am creating an XML file while looping through an array using underscore each. In that loop, I need to call an external resource to retrieve a value to write an XML element for this specific item in the array.
I'm am confused as how to retrieve the value from the external resource while maintaining the order of the loop so that the value is included in the correct item in the array.
I'm returning a Promise in the function that retrieves the value, but this is clearly incorrect.
import Promise from 'bluebird';
import XMLWriter from 'xml-writer';
import _ from 'underscore';
import request from 'request';
class Tester {
writeXml() {
let stores = [
{StoreId: 1, LocationId: 110},
{StoreId: 14, LocationId: 110},
{StoreId: 15, LocationId: 110},
];
let xw = new XMLWriter();
xw.startDocument();
xw.startElement('Stores');
// Loop through all the stores to write the XML file.
_.each(stores, (s) => {
xw.startElement('Store')
.startElement('StoreId').text(s.StoreId).endElement()
.startElement('LocationId').text(s.LocationId).endElement()
// Need to call an external resource here to get the
// store code, but unsure how to do this.
this.getStoreCode(s.LocationId, s.StoreId).then((storeCode) => {
xw.startElement('StoreCode').text(storeCode).endElement();
});
xw.endElement();
});
xw.endDocument();
console.log(xw.toString());
}
getStoreCode(locationId, storeId) {
return new Promise((resolve, reject) => {
let apiUrl = 'http://127.0.0.1:3000/api/v1/stores?filter' +
'[where][locationId]=' + locationId +
'&filter[where][storeId]=' + siteId + '&filter[fields][storeCode]=true';
request(apiUrl, (error, response, body) => {
if (!error) {
let result = JSON.parse(body);
return resolve(result[0].storeCode);
} else {
return reject(error);
}
});
});
}
}
new Tester().writeXml();
Promise.all. You should usemapinstead offorEach