【发布时间】: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);
我对异步/等待不是很熟悉。我没发现问题。
【问题讨论】:
-
你用的是什么浏览器?
asyncawait可能不支持那里。 -
考虑使用 request-promise 模块来获得对 Promise 更友好的 API。您现在遇到的问题是在 HTTP 请求完成之前发送的响应存在重大问题,这意味着它可能永远不会完成(因为 Cloud Functions 的工作方式)。
-
@Grabofus 此代码未在浏览器中运行 - 它在 Cloud Functions 中的 node.js 上运行。
标签: javascript node.js async-await google-cloud-firestore google-cloud-functions