在set()之后不执行Firestore then()函数

kt1*_*t14 2 node.js firebase google-cloud-firestore

我正在使用set功能在Firestore中创建一个新文档。我想在set函数将数据推入数据库后使用文档数据。

            // Add each record to their respective heads
        let docRef = headCollectionRef.doc(data.headSlug).collection(recordsCollection)
            .doc(String(data.recordData.sNo))
        docRef.set(data).then(docSnap => {
            agreementData.push(
                docSnap.get().then(data => {
                    return data
                })
            )
        })
Run Code Online (Sandbox Code Playgroud)

中没有任何then()内容被执行。

任何帮助深表感谢

Jef*_*D23 5

set返回Promise<void>,因此您无权访问其中的doc数据then

在这种情况下,异步/等待将使您的代码更易于阅读。

async function cool() {
  const docRef = headCollectionRef.doc(...)

  await docRef.set(data)

  const docSnap = await docRef.get()

  agreementData.push( docSnap.data() )

}
Run Code Online (Sandbox Code Playgroud)

https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#set

  • 这是行不通的。正如问题所说“然后”不起作用,这与“然后”内部的数据无关。所以问题基本上是 set 方法无法随时得到解决。因此,您在等待之后编写的任何代码都不会被执行。至少这对我不起作用。 (2认同)