How To Resolve The Syntax Error : Await Is Only Valid In Async Function?
I have written a code to return some data from asynchronous call using promise. While I try to execute I get 'Syntax Error await is only valid in async function' and also I get Can
Solution 1:
await
can only be called in a function marked as async
.
so, you can make an async IIFE
and call the httpGet
from there.
(asyncfunction(){
var body = awaithttpGet('link');
$.response.setBody(body);
})()
Basically when you use one asynchronous
operation, you need to make the entire flow asynchronous as well. So the async
keyword kindof uses ES6 generator function and makes it return a promise.
You can check this out if you have confusion.
Solution 2:
This is what worked for me.
I initially had:
exports.doSomething = functions.database.ref('/posts/{postId}').onCreate((snapshot, context) => {
// ... const [response] = await tasksClient.createTask({ parent: queuePath, task });
});
But I added the word async
here (before the open parentheses to snapshot) and then the error went away
// here
.onCreate(async (snapshot, context) => {
So now the code is
exports.doSomething = functions.database.ref('/posts/{postId}').onCreate(async (snapshot, context) => {
// ... const [response] = await tasksClient.createTask({ parent: queuePath, task });
});
Post a Comment for "How To Resolve The Syntax Error : Await Is Only Valid In Async Function?"