1

I tried to make a synchronous queries using mongoose ODM using 'await' keyword basing on another post as the example bellow :

 const query= userModel.find({});
 const syncResutlt= await query.exec();
 console.log(syncResutlt);

but I got this error message :

  const result2 = await query.exec();
                        ^^^^^
  SyntaxError: Unexpected identifier

I tried also yield generator keyword, but I get always the same error SyntaxError: Unexpected identifier

for information I have nodeJs V8.

Amiga500
  • 5,874
  • 10
  • 64
  • 117
AHmedRef
  • 2,555
  • 12
  • 43
  • 75

1 Answers1

3

You can only await Promises or a function marked as async, which essentially returns a Promise.

Correct Way

let getUser=async function(user_id){
    let info= await User.findById(user_id);
    console.log(info); // contains user object
}

Incorrect Way

let getUser= function(user_id){
    let info= await User.findById(user_id); //will throw an exception on await keyword
    console.log(info); // contains user object
}

Hope it helps.

Zeeshan Tariq
  • 604
  • 5
  • 10
  • i mad getUser function return the info object, but when i use it in another function like "let data = getUser(1)" => data = {} (empty object) – AHmedRef Jul 27 '18 at 14:20