2017-08-17 91 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]), []))