2017-08-17 17 views
0

我有這樣的代碼:減法'數組累加器中不能使用推式方法嗎?

let fullConversations = conversationIdsByUser.reduce(async function(acc, conversation) { 
          const message = await MessageModel.find({ 'conversationId':conversation._id }) 
                   .sort('-createdAt') 
                   .limit(1); // it returns an array containing the message object so I just get it by message[0] 


          return acc.push(message[0]); 
          },[]); 

這裏我的累加器是一個數組,消息[0]是,我要推的對象。但我有這個錯誤:

(node:516) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: acc.push is not a function

幫助?

回答

0

這是因爲Array.prototype.push()返回數組的新長度,而不是數組本身。您的代碼將通過reducer的一次迭代運行,將累計值設置爲整數,然後在下一次迭代時失敗。

的修復纔剛剛返回數組在修改之後:

let fullConversations = [{a: 1}, {b: 2}].reduce(function(acc, next) { 
 
    console.log(acc.push(next)) 
 
    
 
    return acc 
 
}, []); 
 

 
console.log(fullConversations)

但是請注意,你應該總是通過一個純粹的功能Array.prototype.reduce()。保持這個規則本來可以讓你擺脫這個問題。例如:

console.log([{a: 1}, {b: 2}].reduce((mem, next) => mem.concat([next]), []))