【问题标题】:How to use multiple async/await functions?如何使用多个异步/等待功能?
【发布时间】:2020-02-15 14:41:21
【问题描述】:

我在部署函数时出错: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);

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

【问题讨论】:

  • 你用的是什么浏览器? async await 可能不支持那里。
  • 考虑使用 request-promise 模块来获得对 Promise 更友好的 API。您现在遇到的问题是在 HTTP 请求完成之前发送的响应存在重大问题,这意味着它可能永远不会完成(因为 Cloud Functions 的工作方式)。
  • @Grabofus 此代码未在浏览器中运行 - 它在 Cloud Functions 中的 node.js 上运行。

标签: javascript node.js async-await google-cloud-firestore google-cloud-functions


【解决方案1】:

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

应该是:

//...   

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

//...

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

【讨论】:

  • await 在非async 函数中将以 "SyntaxError: await 仅在异步函数和异步生成器中有效" 结尾
  • 啊,是的!所以实际上问题可能在于 OP 是 awaiting 一个 async 函数......
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 2023-04-08
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
相关资源
最近更新 更多