Node.js 云功能“get() 中的 firestore set() 如果不存在”无法正常工作?

Posted

技术标签:

【中文标题】Node.js 云功能“get() 中的 firestore set() 如果不存在”无法正常工作?【英文标题】:Node.js cloud function "firestore set() inside get() if not exists" is not working correctly? 【发布时间】:2019-03-03 12:11:02 【问题描述】:

这是我正在努力实现的目标

if user is exist in firestore 
      show the data 
else
      add it to firestore

下面是我的代码

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const WebhookClient = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp(
  credential: admin.credential.applicationDefault()
);

var db = admin.firestore();
const settings = timestampsInSnapshots: true;
db.settings(settings);

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => 
    const agent = new WebhookClient( request, response );

    function save(agent) 
        const usersRef = db.collection('users').doc('someid');
        usersRef.get().then(function(doc) 
            if(doc.exists) 
                let existingUser = doc.data();
                console.log("Document is already exists " + existingUser.userName);
                agent.add('Hello ');
             else 
                console.log("Document creation is started");
                usersRef.set(
                    userName : 'somename'
                );
                agent.add('Welcome ');
            
        ).catch(function(error) 
            console.error("Error writing document: ", error);
            agent.add('Failed to login!');
        );
    
    let intentMap = new Map();
    intentMap.set('dialogflow-intent-name',save);
    agent.handleRequest(intentMap);
);

但上面代码的执行它会启动云功能并首先终止,我的聊天机器人没有得到任何响应,但执行后日志就像

函数执行开始 函数执行耗时 404 毫秒,已完成 状态码:200 “文档已存在 someusername

【问题讨论】:

能否请您添加完整的云功能代码?您在答案中显示的代码是如何触发的? 它只是在触发的特定对话流“意图”上执行的功能代码 不等待写入数据 agent.add() 是异步的吗?它会返回一个承诺吗? 你怎么称呼save(agent)?? 【参考方案1】:

DocumentReference.set 返回一个 Promise,而您无需等待它完成。因此,如果您从以下位置更改代码,它应该可以工作:

usersRef.set(
    userName : 'somename'
);
... rest of the code

usersRef.set(
    userName : 'somename'
).then(result => 
    ... rest of the code
)

【讨论】:

因为有问题提到“文档已经存在某个用户名”被记录...这意味着控制进入 if 语句,那么这个承诺问题将如何发生,因为它在 else 部分。 .. ?

以上是关于Node.js 云功能“get() 中的 firestore set() 如果不存在”无法正常工作?的主要内容,如果未能解决你的问题,请参考以下文章

Node.js 实现存储服务的下载功能包含前后端代码

发送身份验证承载令牌时出现 Cors 策略错误 - node.js(谷歌云功能)

Node.js学习笔记

解析错误:Firebase 云函数中出现意外的令牌 selectWinner - Node.js V10

谷歌云 pubsub node.js 客户端与谷歌云功能不兼容

FCM - node.js 中的计时器功能