firebase 实时数据库中的不同目录访问以实现对话流

different directory access in firebase realtime database for dialogflow fulfillment

我是 node.js(firebase 函数)和 Dialogflow fulfillment 的新手,我想在不同的目录中检索数据。首先是查看最近的商店,然后查看不同目录中商店的库存,但我有问题return。那我该如何解决呢?

app.intent('location_checking - yes',(conv)=> {
  var store= database.ref('store');
  var inventory = database.ref('inventory);
  var keystore=[];
  return store.orderByKey().on("child_added", function(snapshot){
    keystore.push(snapshot.key)
  })
  return inventory.child(keystore).on("value", function(snapshot){
    var tomato =snapshot.val().tomato;
    //and then check the nearest store with available stock
  })
})

您有一些问题,其中一些是概念性的。

首先是您正在使用 on() 和“child_added”事件。但由于这是在 Intent Handler 内部发生的,它只会在用户执行某些操作时被触发,因此您不能同时监听常规事件并对它们做出反应。相反,您可能应该将 once() 与“值”事件一起使用 - 这样您就可以查询所需的值并使用它们。

其次,如果您正在执行任何异步操作,则 Intent Handler 希望您 return Promise - 例如,任何需要回调处理程序的操作。这将需要对如何调用 once() 进行一些重组,因此它们 return 是一个 Promise,然后您在 .then() 块中采取行动。由于您可以使用 .then() 将 Promises 链接在一起,因此您可以通过这种方式进行多次调用。

我不确定按键排序是否能让您找到“最近”的商店,但我暂时忽略它以说明其余代码。

所以你的那部分代码可能看起来像

return store.orderByKey().once("value")
  .then( snapshot => {
    // Handle the results
    // ...

    // Make the next query
    return inventory.child( childKey ).once("value");
  })
  .then( snapshot => {
    // Handle the inventory results
  });

您也可以通过 async/await 将 Intent Handler 设为异步函数,然后在数据库调用中调用 await 来完成此操作。可能是这样的。

app.intent('location_checking - yes', async (conv) => {
  const store= database.ref('store');
  const inventory = database.ref('inventory);

  //...

  const storeSnapshot = await store.orderByKey().once("value");
  // Do something with the store snapshot

  const inventorySnapshot = await inventory.child( childKey ).once("value");
  // Do stuff with the inventory snapshot
})