在foreach循环中获取主干模型

fetch backbone model inside a foreach loop

本文关键字:模型 获取 foreach 循环      更新时间:2023-09-26
    this.shipperModel = new shipperModel();
    this.collection = new packetListCollection(this.options.packetData);
    this.listenTo(this.collection, "change", this.render);
    this.listenTo(this.collection, "add", this.render);
    this.finalArry = [];
    self.collection.each(function (modelData) {
        self.shipperModel.fetch({
            data: {
                facility_id: modelData.facility_id ? modelData.facility_id : 0
            }
        }).then(function (response) {
            console.log(response.records);
            self.finalArry.push(response.records);
        })
    });
    console.log(self.finalArry);

我的数组总是作为空白,即使有数据在响应中,我如何确保结果得到显示,只有在所有上述提取完成后。

这是因为您在then()闭包之外记录数组。

this.finalArry = [];
self.collection.each(function (modelData) {
  self.model.fetch({
    data: {
      facility_id: modelData.facility_id ? modelData.facility_id : 0
    }
  })
  .then(function (response) {
    console.log(response.records);
    self.finalArry.push(response.records);
    console.log(self.finalArry);
  });
});

fetch()是一个异步方法,所以你原来的console.log()在任何网络调用成功之前触发。

Oscar Linde的回答是值得注意的——这可能不是你想要的初始数据水合化方式。

完全重新获取整个集合而不是重新获取每个模型不是更好吗?

无论如何,回到原来的问题,你正在寻找的是javascript的承诺。我想如果我要在评论中解释它,可能会有点令人困惑。也许你可以看看https://api.jquery.com/category/deferred-object/或只是谷歌javascript承诺,我相信你会找到一些东西。

也许这就是你要找的(未经测试):

var requests = [],
  self = this;
this.finalArry = [];
self.collection.each(function (modelData) {
  // Push all requests wrapped in a function into an array
  requests.push(function () {
    return self.model.fetch({
      data: {
        facility_id: modelData.facility_id ? modelData.facility_id : 0
      }
    }).then(function (response) {
      console.log(response.records);
      self.finalArry.push(response.records);
    });
  });
});
// Run all requests and map the return value(a promise)
requests = _.map(requests, function (req) {
  return req();
});
// When all requests are done, log
$.when.apply($, requests).then(function (response) {
    console.log(self.finalArry);
});

至少我不建议使用async: false,它会导致糟糕的用户体验。