首页 > 解决方案 > 如何使用多个异步/等待功能?

问题描述

部署功能时出现错误:error Parsing error: Unexpected token saveLastReview.

我需要获取一些文档值,然后调用 url 请求,然后在我的文档中设置数据。

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);

我对异步/等待不是很熟悉。我没发现问题。

标签: javascriptnode.jsasync-awaitgoogle-cloud-firestoregoogle-cloud-functions

解决方案


看起来您在 中的回调request缺少async关键字。可能会导致您看到的错误,这与您所在的行有关await,这在非异步函数中没有任何意义。

应该是:

//...   

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

//...

编辑:如评论中所述,可能不是这样。但我也注意到这saveLastReview是一个async函数本身,我不知道async函数在被await编辑时的行为。如果我首先提到的内容不能解决问题,也许是另一种调查途径。


推荐阅读