Ad

How To Use Multiple Async/await Functions?

I have an error when I deploy my functions : error Parsing error: Unexpected token saveLastReview.

I need to get some document values, then call a url request, then set data in my document.

async function getValue() {

  try {
    var doc = await admin.firestore().collection('mycollec').doc('mydoc').get();
    var data = doc.data()

    return data;

  } catch(e) {

    console.log(e);
    return null;
  }   
}

async function saveLastReview(authorName) {

  var rating = "4";
  var title = "my title";
  var content = "my content";

  let data = {
      rating : rating,
      title: title,
      content: content
  };

  try {
    var doc = await admin.firestore().collection('mycollec').doc('mydoc').collection('reviews').doc(authorName).set(data);
    return doc;

  } catch(e) {

    console.log(e);
    return null;
  } 
}


app.get('/hello-world',  async(req, res) => {

  var data = await getValue();


  if (data === null) {
      request("https://itunes.apple.com/gb/rss/customerreviews/id=284882215/sortBy=mostRecent/json", function (error, response, body) {

        //code to get authorname from the response

        var result = await saveLastReview(authorname);

        //check if doc was set correctly
        //do something

      })
  }

  return res.status(200).send("sent !");

});
module.exports.app = functions.https.onRequest(app);

I'm not very familiar with async/await. I don't find the problem.

Ad

Answer

It looks like your callback in the request is missing the async keyword. Might lead to the error you are seeing, which relates to the line where you await, which means nothing in a non-async function.

Should probably be :

//...   

request("https://itunes.apple.com/...", async function (error, response, body) {

//...

EDIT: as mentioned in the comment, that is maybe not it. But I also notice that saveLastReview is an async function itself, and I don't know how async function behave when they are awaited. Maybe another avenue of investigation if what I mentioned first doesn't fix the issue.

Ad
source: stackoverflow.com
Ad