I wrote this code in lib/helper.js
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunct
To use await
, its executing context needs to be async
in nature
As it said, you need to define the nature of your executing context
where you are willing to await
a task before anything.
Just put async
before the fn
declaration in which your async
task will execute.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Explanation:
In your question, you are importing a method
which is asynchronous
in nature and will execute in parallel. But where you are trying to execute that async
method is inside a different execution context
which you need to define async
to use await
.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Wondering what's going under the hood
await
consumes promise/future / task-returning methods/functions and async
marks a method/function as capable of using await.
Also if you are familiar with promises
, await
is actually doing the same process of promise/resolve. Creating a chain of promise and executes you next task in resolve
callback.
For more info you can refer to MDN DOCS.