Reputation: 1
I've a requirement where I have to call another function for a record of data before I actually perform next set of operations.
so here's what I'm doing but it doesn't work. function a is stored in a common library abc
var a = (req,callBack) =>{
DB Operation
.
.
.
.
callBack(null,result);
}
var b = (req,callBack) =>{
const c = await abc.a(req,response);
DB Operation
.
.
.
.
.
callBack(null,result);
}
when I do const c = await abc.a(req,response); it gives me error "await is only valid in async function" but I've seen examples where await is used like this.
can you please help me with this.
Upvotes: 0
Views: 72
Reputation: 29159
await
is only valid if the called function returns a promise
, or is marked async
.
Furthermore, await
must be used from within an async
function.
Both are false in your case.
Don't use async/await...
var b = (req,callBack) =>{
abc.a(req,c=>{
DB Operation
callBack(null,result);
});
}
You can wrap your functions inside async
functions if you insist on using that syntax.
Upvotes: 0
Reputation: 71
You'r code would like.
async function a () {
const b = await funcX()
}
or
const b = async () => {
const b = await funcX()
}
like that
Upvotes: 0
Reputation: 208
You are not using async/await properly. Await only works inside async functions. So make your function async.
var b = async (req,callBack) =>{ // made this function async
abc.a(req, (_, res) => {
DB Operation
.
.
.
.
.
callBack(null,result);
});
}
Upvotes: 1