如何使用 Firestore 在 DialogFlow fullfilment 上显示来自 snap 的值

How to display a value from snap on DialogFlow fullfilment using Firestore

我正在尝试显示存储在 Firestore 上的信息。

这是我的数据库。

我想显示 "definicion" 值。

这是我对 Js 的 Intent(使用 Nodejs):

    app.intent('my.def.intent', (conv) => {
    // Trying to get Data from firestone DB,
        var platformRef = db.collection("plataformas").doc("slack");
        var getDef =  platformRef.get()
        .then( snap =>{
            var dat = "";
            if (snap.exists) {
                dat =  snap.data("definicion");
            }
             return dat;
        })
        .catch( err => {
            console.log("error...", err);
        });
    // This is the response for Actions on Google
    conv.ask(new SimpleResponse({
                  speech:"This is the def: " + getDef,
                  text:"This is the def: " + getDef,
                }));
    });

此代码在 ActionsOnGoogle 模拟器上显示如下内容:

这是定义:[objecto Promise]

我不明白这里发生了什么。为什么我不能显示来自 "definiciones" 的信息,而是有一个 [object promise]?我怎样才能显示信息?

谢谢!!!

对 platformRef.get().then( ... ) 的调用是异步的并且 return 是一个 Promise,因此当您访问 getDef 的值时,它的值是一个 Promise。

要修复它,您应该将 conv.ask 代码放在上面的 .then 块中。但是,由于您已经可以访问内部的 snap 值,因此您实际上并不需要 getDef 的值,可以直接使用 snap 。最后,您需要 return 从您的意图函数中获得该承诺的价值。把这些放在一起给出:

app.intent('my.def.intent', (conv) => {
   // Trying to get Data from firestone DB,
   var platformRef = db.collection("plataformas").doc("slack");
   return platformRef.get()
            .then( snap => {
              var dat = "";
                if (snap.exists) {
                  dat =  snap.data("definicion");
                }
               // This is the response for Actions on Google
               conv.ask(new SimpleResponse({
                  speech:"This is the def: " + dat,
                  text:"This is the def: " + dat,
               }));
           })
           .catch( err => {
             console.log("error...", err);
           });
 });

我建议看一下官方示例 - dialogflow-updates-nodejs。它还使用 Firestore,可以帮助编码。