[英]Ordered JavaScript Promise in each loop
我正在創建XML文件,同時使用下划線循環遍歷數組。 在該循環中,我需要調用一個外部資源來檢索一個值,以為此數組中的此特定項編寫XML元素。
我很困惑如何在保持循環順序的同時從外部資源中檢索值,以便將該值包含在數組的正確項目中。
我在檢索值的函數中返回一個Promise,但這顯然是不正確的。
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();
未經測試,但這是要走的路(或更適度地說,是走的路)。
writeXml(stores) {
let xw = new XMLWriter();
xw.startDocument();
xw.startElement('Stores');
return Promise.map(stores, (store) => {
return this.getStoreCode(store.LocationId, store.StoreId).then((storeCode) => {
store.StoreCode = storeCode;
return store;
});
}).each((storeWithStoreCode) => {
xw.startElement('Store');
_.each(['StoreId', 'LocationId', 'StoreCode'], (prop) => {
xw.startElement(prop).text(storeWithStoreCode[prop]).endElement();
});
xw.endElement();
}).then(() => {
xw.endDocument();
return xw;
});
}
和
writeXml([
{StoreId: 1, LocationId: 110},
{StoreId: 14, LocationId: 110},
{StoreId: 15, LocationId: 110},
]).then((xw) => {
console.log(xw.toString());
});
用英語,它使用Promise.map()
將普通store
對象投影到Promises中,以用於具有StoreCode
屬性的商店對象。
然后,將其中的.each()
寫入XML編寫器。
最后,整個鏈都解析為XML writer對象本身,您可能希望將其更改為其他結果。
使用promise的函數應返回一個promise(或調用某種回調),以便調用代碼有機會知道該函數何時完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.