请问这一步为啥要分 2 次写?

2020-09-04 14:35:55 +08:00
 lithium148

const countResult = await db.collection('todos').count() const total = countResult.total console.log(total) //total 为 6

const total = await db.collection('todos').count().total
console.log(total)
//total 为 null

谢谢!

1222 次点击
所在节点    问与答
5 条回复
Vegetable
2020-09-04 14:51:04 +08:00
试试加了括号的。
const total = (await db.collection('todos').count()).total

可以理解为,await 生效的那次调用,是最后一个点
fuzhuo233
2020-09-04 17:34:48 +08:00
await 的优先级应该低于取 total 的值,而需要 await 先 resolve Promise,才能得到结果。话说优雅一点标准带语法糖不是用 const {total} = await db.collection('todos')
keepeye
2020-09-04 17:39:32 +08:00
await 右边表达式的结果
.count() 本身是异步的,要等 await 成功之后才能获取到 total
keepeye
2020-09-04 17:40:15 +08:00
count().total 是错的 count()是个 Promise 对象
azh7138m
2020-09-04 21:38:55 +08:00
(await db.collection('todos').count()).total

await db.collection('todos').count().total 实际是 await undefined

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/704206

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX