. Advertisement .
..3..
. Advertisement .
..4..
I am writing my program, then error syntaxerror: await is only valid in async function shows up.
This is my code in commonFun.js file:
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunction;
After using it in a different file
var helper = require('./commonFun.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
I got error:
"await is only valid in async function"
Tell me the way to solve this problem, please.
Thanks a lots.
Solution:
Solution 1.
The issue refers to
start
rather thanmyfunction
. Here, you wait for themyfunction
to complete before returning a promise that will also be awaited. Point out that you may return the promise thatmyfunction
returned instead of using the async hashtag on the function.Solution 2.
This error message actually referred to the map function’s lack of a “async” designation. By removing the “await” call from the map function and finding another way to achieve the desired behavior, the syntaxerror: await is only valid in async function can be fixed.