reduce'数组累加器中没有推送方法?

时间:2017-08-17 17:56:10

标签: javascript mongoose

我有这段代码:

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:未处理的承诺   rejection(rejection id:2):TypeError:acc.push不是函数

帮助?

1 个答案:

答案 0 :(得分:3)

这是因为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]), []))

相关问题