0

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.

Nick
  • 1
  • 4
  • I think the error message is somewhat self-explanatory... is it not? [Possible duplicate](https://stackoverflow.com/q/49432579/1541563) – Patrick Roberts Oct 16 '19 at 05:03
  • _"but I've seen examples where await is used like this"_ - Then you've missed the `async` in the examples – Andreas Oct 16 '19 at 05:03

3 Answers3

1

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);
    });
}
shubham-gupta
  • 208
  • 1
  • 5
  • That dint help it gives a warning 'await' has no effect on the type of this expression. and when I test it it doesnt wait for response. – Nick Oct 16 '19 at 05:16
  • If function a which is a library function returns a callback. Then you don't need to use async/await. You can just have your data in callback response. – shubham-gupta Oct 16 '19 at 05:22
0

You'r code would like.

async function a () {
  const b = await funcX()
}

or

const b =  async () => {
  const b = await funcX()
}

like that

ucode
  • 31
  • 1
  • 1
  • 5
0

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.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78