【问题标题】:Promise/async-await with mongoose, returning empty arrayPromise/async-await with mongoose,返回空数组
【发布时间】:2017-10-21 00:27:14
【问题描述】:

控制台最后返回空数组。 控制台在 ids.map 函数完成之前运行

var ids = [];
var allLync = []
var user = await User.findOne(args.user)
ids.push(user._id)
user.following.map(x => {
    ids.push(x)
})
ids.map(async x => {
    var lync = await Lync.find({ "author": x })
    lync.map(u => {
        allLync.push[u]
    })
})

console.log(allLync)

我做错了什么?

【问题讨论】:

  • lync 的值是多少 - 尝试添加 console.log(lync) 以查看 Lync.find({ "author": x }) 会返回给您什么 - 顺便说一句,.map 的使用非常糟糕 - 顺便说一句你写的,你也可以使用.forEach
  • @JaromandaX 你是对的,但有点小问题:OP 实际上确实需要.map,因为他们需要在log 之前等待他们的承诺
  • 除了返回的值我的.map 并没有被实际使用 - 我说他使用 .map 的方式他也可以使用 .forEach .... 但是 .map 是正确的方法,如果它正确使用

标签: javascript node.js mongoose promise async-await


【解决方案1】:

不等待.map 代码,因此console.log 发生在映射发生之前。

如果您想等待地图 - 您可以使用 Promise.allawait

var ids = [];
var allLync = []
var user = await User.findOne(args.user)
ids.push(user._id)
user.following.map(x => {
    ids.push(x)
})
// note the await
await Promise.all(ids.map(async x => {
    var lync = await Lync.find({ "author": x })
    lync.map(u => {
        allLync.push(u); // you had a typo there
    })
}));

console.log(allLync)

请注意,由于您使用的是.map,因此您可以显着缩短代码:

const user = await User.findOne(args.user)
const ids = users.following.concat(user._id);
const allLync = await Promise.all(ids.map(id => Lync.find({"author": x })));
console.log(allLync); 

【讨论】:

  • 成功了,我从你那里学到了一个新概念。非常感谢! :)
【解决方案2】:

如果您不介意使用 bluebird,Promise.map() 现在是一个更简洁的选项。 它可能看起来像:

const user = await User.findOne(args.user);
const ids = users.following.concat(user._id);
const allLync = await Promise.map(ids, (id => Lync.find({"author": x })));
console.log(allLync); 

http://bluebirdjs.com/docs/api/promise.map.html。我真的很喜欢使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2018-03-27
    • 2019-09-16
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多