2015-10-20 375 views
1
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); 

我的數組內骨幹模型總是即使是怎麼做的響應數據我確保結果得到所有上述取完成後,才顯示爲空白。取foreach循環

回答

2

那豈不是更好地完全重新獲取整個集合,而不是重新獲取每個模型?

不管怎樣,回到原來的問題,你正在尋找的是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,它有助於一個不好的用戶體驗。

+0

我正在獲取的模式是不相同的類型集合對不起我命名搞砸了的已經更新 – vini

+0

好吧,我會回來秒一些示例代碼! –

+1

@vini:我現在添加了一些示例代碼。我不認爲'async:false'是一個好主意。也許你可以像我在示例代碼中那樣做。對承諾的一般性閱讀不會受到傷害,因爲它真的很好知道! –

3

這是因爲你登錄你的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()大火成功。

奧斯卡林德的答案是明顯的 - 這可能不是你想要做的初始數據水化的方式。