【发布时间】:2018-07-20 20:34:41
【问题描述】:
我正在使用 Node.js 和猫鼬,但这个问题纯粹是关于 async await 部分。我写了这段代码,它工作正常。
router.get('/applications/:_id', async (req, res, next) => {
var posting = await Posting.findOne({'_id': req.params._id, 'creatorId': req.user._id, 'visible': true}); // await here
var seekers = await Account.find({'accType': 'seeker', 'blocked': false});
console.log(posting.applications) // no await here
// ^^^ this will log the applications array.
res.render('users/employer/applications', {
user: req.user,
title: 'Job applications',
applications: posting.applications,
seekers: await seekers,
})
});
但如果我这样做:
router.get('/applications/:_id', async (req, res, next) => {
var posting = Posting.findOne({'_id': req.params._id, 'creatorId': req.user._id, 'visible': true}); // remove await from here
var seekers = Account.find({'accType': 'seeker', 'blocked': false});
console.log(await posting.applications); // add await here
// ^^^ this will log undefined
res.render('users/employer/applications', {
user: req.user,
title: 'Job applications',
applications: await posting.applications,
seekers: await seekers,
})
});
我无法打印出posting.applications 数组。 (未定义)。
但我可以像这样打印出整个对象:
router.get('/applications/:_id', async (req, res, next) => {
var posting = Posting.findOne({'_id': req.params._id, 'creatorId': req.user._id, 'visible': true});
// ^^^ remove await from here
var seekers = Account.find({'accType': 'seeker', 'blocked': false});
console.log(await posting); // add await here
// ^^^ this will log the object
console.log(await posting.applications); // this will log undefined
res.render('users/employer/applications', {
user: req.user,
title: 'Job applications',
applications: await posting.applications,
seekers: await seekers,
})
});
我认为 await 会停止代码的执行,直到它完成。那么,如果对象存在,为什么我无法获取属性?
[重复注释] 我也在通过将对象发送到视图来检查这一点。它在视图中的行为方式与在 console.log 中的行为方式相同。这是一个简化的例子。
【问题讨论】:
-
我也在通过将对象发送到视图来检查这一点。它在视图中的行为方式与在 console.log 中的行为方式相同。这是一个简化的例子。
-
@Isaac - 我不这么认为,这似乎主要是混淆了
await的使用方式。
标签: javascript node.js asynchronous async-await