简体   繁体   English

使用 function 在 map 中返回值?

[英]Using function to return value in a map?

Im mapping over an array of objects and adding a value for "latestMessage"我映射一组对象并为“latestMessage”添加一个值

The latest() function searches for the message and returns and object. latest() function 搜索消息并返回 object。 But the reult of the map does not contain the new property.但是 map 的结果不包含新属性。 If I remove the latest function and just put a string though it works.如果我删除了最新的 function 并只放置一个字符串,尽管它可以工作。

function latest(userId) {
  Chat.findOne({ $or: [{ to: userId }, { from: userId }] }, {}, { sort: { createdAt: -1 } }, function (err, msg) {

    return msg

  })
}

Does not work:不工作:

let array = users.map(v => ({ ...v._doc, latestMessage: latest(v._id) }))

Works:作品:

let array = users.map(v => ({ ...v._doc, latestMessage: {test: 'test'} }))

Since Chat.fineOne is running a callback function, you have to do your logic in that function.由于Chat.fineOne正在运行回调 function,因此您必须在 function 中执行您的逻辑。 I'm not sure how they rest of your application is setup, but you might be able to create the object and pass it to your query.我不确定您的应用程序的 rest 是如何设置的,但您也许可以创建 object 并将其传递给您的查询。 The query can update the object when the callback happens.当回调发生时,查询可以更新 object。 Note, this will be after the map has already been created since it's async .请注意,这将在 map 已经创建之后,因为它是async

let array = users.map(v => {
  let value = { ...v._doc, latestMessage: "" };
  setLatest(value);
  return value;
});

function setLatest(value) {
  Chat.findOne({ $or: [{ to: value._id }, { from: value._id }] }, {}, { sort: { createdAt: -1 } }, function (err, msg) {
    value.latestMessage = msg;
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM