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 - 在 foreach 循环中获取主干模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33243787/