繁体   English   中英

每个循环中有序的JavaScript Promise

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM