【问题标题】:Items being returned out of order after mapping with a promise - Ionic/Angular/Typescript使用承诺映射后,项目被乱序退回 - Ionic/Angular/Typescript
【发布时间】:2018-04-06 21:29:21
【问题描述】:

我正在从数据库中检索供稿的项目,它们需要保持我检索它们的顺序(因为它是供稿)。现在,我从查询中获取数组并映射它。毕竟,它会乱序显示提要对象。这是我的代码:

    let cacheKey = 'promos';
    let promises_array:Array<any> = [];
    let mapped;
    this.cache.removeItem(cacheKey);

    this.cache.getItem(cacheKey).catch(() => {
      let store = [];

      this.list2 = this.af.list('/promos', {
      query: {
        limitToLast: 10
      }});

      this.subscription4 = this.list2.subscribe(items => {
        mapped = items.map((item) => {
          return new Promise((resolve,reject) => {
            let storageRef = firebase.storage().ref().child('/settings/' + item.customMetadata.username + '/profilepicture.png');

            storageRef.getDownloadURL().then(url => {
              console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
              item.customMetadata.picURL = url;
              store.push(item.customMetadata);
              resolve();
            }).catch((e) => {
              console.log("in caught url !!!!!!!$$$$$$$!!");
              item.customMetadata.picURL = 'assets/blankprof.png';
              store.push(item.customMetadata);
              resolve();
            });


          })
        })

        console.log(JSON.stringify(mapped) + "    mappped things");



        this.startAtKey = items[0].$key;
        this.lastKey = this.startAtKey;

        let results = Promise.all(mapped);
        results.then(() => {
        //setTimeout(() => {

          this.items = store.reverse();
          //this.classesListArray.reverse();   
          console.log(JSON.stringify(this.items) + " value value vlaue items");
          return this.cache.saveItem(cacheKey, this.items);
        //}, 3000);

        })
      })
    }).then(data => {
      this.items = data;
    })

我猜图像每次都以不同的速率加载,并且由于加载时间的原因被映射到了某种混乱状态,即使 map 应该保持数组的顺序。另一件事是,我不确定从请求中返回的内容是否实际上是一个数组。当我在下标中记录typeof items 时,它返回object,但使用JSON.stringify 它显示了一个数组结构——这可能是它失去顺序的原因吗?它实际上不是一个数组?

【问题讨论】:

    标签: arrays angular typescript object ionic-framework


    【解决方案1】:

    在您拥有所有物品后订购。

    store.sort((a,b) => {
        return a.prop - b.prop;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 2017-03-07
      • 2016-10-25
      • 2016-08-05
      • 2016-03-18
      • 1970-01-01
      • 2021-07-28
      • 2017-12-21
      相关资源
      最近更新 更多