简体   繁体   中英

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.

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 await ed. Maybe another avenue of investigation if what I mentioned first doesn't fix the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM