0

I am trying to assign the variable "dish_data" to data that is returned from "dish_ref.get()," which returns a promise.

let dish_data;
var get_dish_data = dish_ref.get()
        .then(doc => {
            console.log('doc: ', doc);
            console.log('doc: ', doc.data());
            dish_data = doc.data();
            console.log('dish_data in promise: ', dish_data);
        });

 console.log('dish_data after promise: ', dish_data);
 const num_ratings = dish_data['num_ratings'];

"dish_ref" is a Google Firestore document. The console log for "doc" and "doc.data()" shows a firestore document and the dictionary data respectively. The console log also shows "dish_data" containing the information from "doc.data()" when within the promise but after the promise, "dish_data" is undefined.

I've tried creating an async function as follows...

async function myFunc() {

    var get_dish_data = await dish_ref.get();

  }

dish_ref.get().then(myFunc);

var dish_data = get_dish_data.data();

but I got a syntax error saying function was an unexpected token.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
A. Ash
  • 27
  • 1
  • 4
  • Just put all the code that uses the promise results inside the callback – Bergi Aug 08 '18 at 19:43
  • I decided to go with this route but it did make my code more messy. I would have preferred using async and await but like I wrote in my post, I keep getting that syntax error, and after some googling, it looked like an outdated Node version was the culprit but I'm using the latest version of Node so I have no idea what the issue is. – A. Ash Aug 08 '18 at 20:52

1 Answers1

0

get() (as well as all functions that return a promise) are asynchronous, meaning they return immediately. The callback provided to then() gets executed some time later when the async work is complete.

Your code looks like it's assuming that get() blocks execution of this code, which it does not. The subsequent code that accesses dish_data is going to execute immediately after get() returns, which means it will be undefined. It won't get defined until your callback is finally executed.

If you want to use the results of the get(), you should only do that in the callback, or pass it along to some other function from there.

If you want to use async, then you will have to also use await to effectively pause the execution of the function until get() yields its results.

You can watch my video series on using promises and async/await, which may help explain things.

https://www.youtube.com/watch?v=7IkUgCLr5oA

https://www.youtube.com/watch?v=652XeeKNHSk

https://www.youtube.com/watch?v=d9GrysWH1Lc

https://www.youtube.com/watch?v=TCYhr_UMZkI

https://www.youtube.com/watch?v=Jr7pDZ1RAUg

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441