为什么需要从dialogflow的firestore查询中“返回” agent.add?

问题描述 投票:0回答:1

我有一个对话流实现中的函数,当一个意图匹配时会调用该函数。它查询Firestore数据库。首先,我不太明白为什么查询本身需要return关键字,以及为什么需要返回agent.add。我假设它与诺言的工作方式有关。

function one(agent) {

    let userRef = db.collection('users');
    let queryRef = userRef.where("uId", "==", "1");

    return queryRef.get().then(function(doc) {
        if (doc.exists) {
            console.log("Document data:", doc.data());
            return agent.add(some info from the doc);
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
            return agent.add("error");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

}

另一件事,我注意到我不太了解。如果我具有函数1和函数2并将查询放入函数2中,则它将无法工作。

function one(agent) {

    function two();

}

function two() {

    function one(agent) {

        let userRef = db.collection('users');
        let queryRef = userRef.where("uId", "==", "1");

        return queryRef.get().then(function(doc) {
            if (doc.exists) {
                console.log("Document data:", doc.data());
                return agent.add(some info from the doc);
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
                return agent.add("error");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });

    }
}
javascript google-cloud-firestore dialogflow
1个回答
0
投票

[当您在DialogFlow中运行此代码时,它将在Google的Cloud Functions环境中运行。 Google只会在需要时使Cloud Functions运行时保持可用状态。

默认情况下,当您的代码的最后}运行时,Cloud Functions会停止容器。但是,在您的情况下,对queryRef.get()的调用是异步发生的,因此在执行}之前仍在运行。为了防止Cloud Functions在数据库调用完成之前终止代码,请将返回值从queryRef.get()返回给Cloud Functions,这就是所谓的promise。

当Cloud Functions从您的代码中获得承诺时,它将使该功能保持活动状态,直到该承诺完成为止。因此,通过从queryRef.get()返回Promise,您的Cloud Functions环境将保持活动状态,直到数据库调用完成。

agent.add同样是一个异步调用,它将响应写入调用方代理。为防止该调用被Cloud Functions提前终止,您还需要将结果从agent.add返回给Cloud Functions。

根据承诺的性质,当您在then()内部返回承诺时,承诺实际上会冒出。因此,Cloud Functions最终要等到数据库查询响应编写都完成。

© www.soinside.com 2019 - 2024. All rights reserved.