I wrote this code in lib/helper.js
:
JavaScript
x
6
1
var myfunction = async function(x,y) {
2
.
3
return [variableA, variableB]
4
}
5
exports.myfunction = myfunction;
6
Then I tried to use it in another file :
JavaScript
1
7
1
var helper = require('./helper.js');
2
var start = function(a,b){
3
.
4
const result = await helper.myfunction('test','test');
5
}
6
exports.start = start;
7
I got an error:
JavaScript
1
2
1
await is only valid in async function
2
What is the issue?
Advertisement
Answer
The error is not refering to myfunction
but to start
.
JavaScript
1
6
1
async function start() {
2
.
3
4
const result = await helper.myfunction('test', 'test');
5
}
6
JavaScript
1
17
17
1
// My function
2
const myfunction = async function(x, y) {
3
return [
4
x,
5
y,
6
];
7
}
8
9
// Start function
10
const start = async function(a, b) {
11
const result = await myfunction('test', 'test');
12
13
console.log(result);
14
}
15
16
// Call start
17
start();
I use the opportunity of this question to advise you about an known anti pattern using await
which is : return await
.
WRONG
JavaScript
1
23
23
1
async function myfunction() {
2
console.log('Inside of myfunction');
3
}
4
5
// Here we wait for the myfunction to finish
6
// and then returns a promise that'll be waited for aswell
7
// It's useless to wait the myfunction to finish before to return
8
// we can simply returns a promise that will be resolved later
9
10
// useless async here
11
async function start() {
12
// useless await here
13
return await myfunction();
14
}
15
16
// Call start
17
(async() => {
18
console.log('before start');
19
20
await start();
21
22
console.log('after start');
23
})();
CORRECT
JavaScript
1
23
23
1
async function myfunction() {
2
console.log('Inside of myfunction');
3
}
4
5
// Here we wait for the myfunction to finish
6
// and then returns a promise that'll be waited for aswell
7
// It's useless to wait the myfunction to finish before to return
8
// we can simply returns a promise that will be resolved later
9
10
// Also point that we don't use async keyword on the function because
11
// we can simply returns the promise returned by myfunction
12
function start() {
13
return myfunction();
14
}
15
16
// Call start
17
(async() => {
18
console.log('before start');
19
20
await start();
21
22
console.log('after start');
23
})();
Also, know that there is a special case where return await
is correct and important : (using try/catch)