Ununennium
V2EX  ›  问与答

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

  •  
  •   Ununennium · Sep 4, 2020 · 1668 views
    This topic created in 2082 days ago, the information mentioned may be changed or developed.

    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
    

    谢谢!

    5 replies    2020-09-04 21:38:55 +08:00
    Vegetable
        1
    Vegetable  
       Sep 4, 2020   ❤️ 1
    试试加了括号的。
    const total = (await db.collection('todos').count()).total

    可以理解为,await 生效的那次调用,是最后一个点
    fuzhuo233
        2
    fuzhuo233  
       Sep 4, 2020
    await 的优先级应该低于取 total 的值,而需要 await 先 resolve Promise,才能得到结果。话说优雅一点标准带语法糖不是用 const {total} = await db.collection('todos')
    keepeye
        3
    keepeye  
       Sep 4, 2020
    await 右边表达式的结果
    .count() 本身是异步的,要等 await 成功之后才能获取到 total
    keepeye
        4
    keepeye  
       Sep 4, 2020
    count().total 是错的 count()是个 Promise 对象
    azh7138m
        5
    azh7138m  
       Sep 4, 2020
    (await db.collection('todos').count()).total

    await db.collection('todos').count().total 实际是 await undefined
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2960 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 13:43 · PVG 21:43 · LAX 06:43 · JFK 09:43
    ♥ Do have faith in what you're doing.