[英]async function with cloud functions (syntax error on async)
I have the following code in my index.js:我的 index.js 中有以下代码:
exports.queryAPI = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
return APICall(request.params.searchTerm).then((result) => {
console.log(result);
return result;
}).catch(() => {
return response.status(400).json({ error: 'Something went wrong.' });
})
});
});
async function APICall(search) {
const response = await apicalypse({
queryMethod: "body",
headers: {
'Accept': 'application/json',
'user-key': API_KEY
},
responseType: 'json',
timeout: 1000,
})
.fields(["name"]) // fetches only the name and movies fields
.search(search) // search for a specific name (search implementations can vary)
// .where("age > 50 & movies != n") // filter the results
// .where(["age > 50", "movies != n"]) // same as above
.request(API_URL);
return response.data;
}
When I try to deploy this function I get the following error:当我尝试部署此 function 时,出现以下错误:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:34
async function APICall(search) {
^^^^^^^^
SyntaxError: Unexpected token function
According to my searches I did the function correct with async.根据我的搜索,我用异步做了 function 正确。 Someone that point where I made my mistake?
有人指出我犯了错误吗?
Node.js version 8 is required. 必须安装Node.js版本8。 Do this on your development machine:
在您的开发机器上执行此操作:
nvm install 8.6.1
nvm alias default 8.6.1
Then in your functions
directory, open package.json
and add: 然后在您的
functions
目录中,打开package.json
并添加:
"engines": {
"node": "8"
},
You're probably using a node version less than 8 on your local machine. 您可能在本地计算机上使用的节点版本小于8。 Version 8 is the first version that supports ES7 async/await syntax.
版本8是第一个支持ES7异步/等待语法的版本。 So, the first thing is to update your local node installation.
因此,第一件事是更新本地节点安装。 Check the version with
node --version
. 使用
node --version
检查版本。
Cloud Functions uses node 6 as a runtime by default, so if you want your deployed code that uses async/await to run, you will also have to tell the Firebase CLI to target node 8. Node 8 support is in beta. Cloud Functions默认情况下使用节点6作为运行时,因此,如果要运行使用async / await的已部署代码,则还必须告知Firebase CLI以目标节点8为目标。Beta 8支持节点8。 You can read about targeting node 8 in the documentation and in this blog .
您可以在文档和此博客中了解有关定位节点8 的信息 。
I'm not sure the reason, but the await
command only works in index.js for me.我不确定原因,但
await
命令只适用于 index.js 对我来说。 If I move the same command to another file and exports
the function, I get the same compilation error as your async
error.如果我将相同的命令移动到另一个文件并
exports
function,我会得到与您的async
错误相同的编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.