How to wait for the promise when using get in Firestore

风格不统一 提交于 2019-12-20 06:14:26

问题


I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?

Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response. I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out. I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response. Can anyone point me in the right direction?

      'use strict';


const functions = require('firebase-functions'); //don't forget this one

// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');

const Firestore = require('@google-cloud/firestore');

var doc;

var question1;

const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');

const config = functions.config();

const WELCOME_INTENT = 'Default Welcome Intent';


const app = dialogflow({debug: true});

async function dbaccess(rando) {


console.log("dbaseaccess started")


var currentquestion2 = 'question-' + rando.toString();

var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff

question1 = cityRef.data().n111




} catch(e) {

//error!
}
console.log("one line above return something");

return rando;


}


app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;






switch (intent) {
 case WELCOME_INTENT:

var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);




const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);

break;


exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

回答1:


You have 2 options: you can use async/await or you can use Promise.then() depending on how you want the code to execute.

Async/await:

async function databasetest {
  var cityRef;
  try{
    cityRef = await db.collection('cities').doc('SF');
    // do stuff
  } catch(e) {
    // error!
  }

Promise.then():

db.collection('cities').doc('SF').then((cityRef) => {
  cityRef.get()
    .then(doc => { /* do stuff */ })
    .catch(err => { /* error! */ });
});



回答2:


maybe a little of work around could help you, I'm not sure yet how you are trying to implement it.

 function databasetest () {
  var cityRef = db.collection('cities').doc('SF');
  return cityRef.get()
  }

// so you can implement it like

databasetest().then(doc => {
 if (!doc.exists) {
   console.log('No such document!');
 } else {
   console.log('Document data:', doc.data());
 }
})
.catch(err => {
  console.log('Error getting document', err);
});

More context would help to understand your use case better :)



来源:https://stackoverflow.com/questions/56408589/how-to-wait-for-the-promise-when-using-get-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!