如何在Dialogflow中使用if else循环显示结果

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

我有用于Dialogflow在Java Actions上执行项目的Javascript代码。对于此代码,如果答案在数据库中,则它将回答,否则它将退出应用程序。所以,我想对这个代码使用else循环,请帮我

 function handleCompanyDetails(agent){   
  const RegNo = agent.parameters.RegNo;
  var ref8 =  admin.database().ref().child("Table/");
  var query8 = ref8.orderByChild("RegNo").equalTo(RegNo);
  return query8.once("value")
     .then(function(snapshot) {  
          snapshot.forEach(function(child) {
              agent.add(`The student placed in  ` + child.val().CompanyName);
              agent.add(new Card({
                  title: ` Name:${child.val().Studentname}
                  Reg No: ${child.val().RegNo}
                  Offer Date: ${child.val().OfferDate} `, 
                  imageUrl: '',
                  text:  `Thanks for using 💁\n  ${child.val().FirstName} 💁`,
                  buttonText: '.com'
              })
           );
        });
     })
  .catch( err => {
    console.error(err);
    agent.add("There was a problem.");
  });
javascript firebase dialogflow actions-on-google dialogflow-fulfillment
2个回答
0
投票

对快照执行操作时使用.then()。因为.once()仅触发一次,所以如果有可用数据,则将执行.then(),您可以使用.catch()退出。检查下面的代码。

function handleCompanyDetails(agent){   
  const RegNo = agent.parameters.RegNo;
  var ref8 =  admin.database().ref().child("Table/");
  var query8 = ref8.orderByChild("RegNo").equalTo(RegNo);
  return query8.once("value")
     .then(function(snapshot) {  
          snapshot.forEach(function(child) {
              agent.add(`The student placed in  ` + child.val().CompanyName);
              agent.add(new Card({
                  title: ` Name:${child.val().Studentname}
                  Reg No: ${child.val().RegNo}
                  Offer Date: ${child.val().OfferDate} `, 
                  imageUrl: '',
                  text:  `Thanks for using 💁\n  ${child.val().FirstName} 💁`,
                  buttonText: '.com'
              })
           })
        })
     .catch( // throw some error)
    }

您可以在这里阅读更多信息,https://firebase.google.com/docs/database/web/read-and-write


0
投票

虽然您可以使用循环来显示结果,但是您的操作方式甚至可能是尝试返回的内容都存在一些问题。

[First-Dialogflow要求您从进行异步调用的任何函数(例如对Firebase数据库的调用)中返回Promise。您当前正在使用回调方法。您应该切换为使用once()来返回一个Promise,这样看起来可能像这样:

return query8.once("value")
  .then( snapshot => {
    // working with snapshot goes here
  })
  .catch( err => {
    console.error(err);
    agent.add("There was a problem.");
  });

第二是如何使用snapshot本身。如果期望得到多个结果,则应注意,您只能用短信和两次基本卡呼叫agent.add()。如果需要多个卡,则可能要使用list或轮播。

如果您希望仅在RegNo上建立索引,看起来像是,那么您应该将其作为路径的一部分并获取快照的值。在这种情况下,您不需要循环。

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