javascript - 如何使用多个异步/等待功能?
问题描述
部署功能时出现错误: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);
我对异步/等待不是很熟悉。我没发现问题。
解决方案
看起来您在 中的回调request
缺少async
关键字。可能会导致您看到的错误,这与您所在的行有关await
,这在非异步函数中没有任何意义。
应该是:
//...
request("https://itunes.apple.com/...", async function (error, response, body) {
//...
编辑:如评论中所述,可能不是这样。但我也注意到这saveLastReview
是一个async
函数本身,我不知道async
函数在被await
编辑时的行为。如果我首先提到的内容不能解决问题,也许是另一种调查途径。
推荐阅读
- laravel - 登录用户的 hasManyThrough 表中的 Laravel、过滤器和 Sum 字段
- apache-kafka - 在 Kafka 中是否可以使用 i18n
- sql - 我有一个 PL/SQL 代码,但我不知道它的作用是什么?
- bash - Bash:用所有模式替换引号外的分号
- javascript - 如何模仿javascript中的刷新行为?
- azure - Azure 事件中心创建 1 个中心的问题
- c++ - glReadPixels() 不准确
- javascript - ChartJs 缩放插件增加了大数据集的 X 轴缩放
- c# - Linq在对象数组上搜索
- python - 如何显示 MyPy 在 PyDev/Eclipse 中运行的结果?