1

I'm trying to return data from an async function to a non async function it always returns a promise here is my code

static async getById(id){
    const db = await mongodb;
    const mongoId = new ObjectID(id);
    return await db.collection(Restaurant.collectionName).findOne({_id:mongoId});
  }
const obj = Restaurant.getById(data);//called in a non async function so i cannot use await 
        return new Restaurant(obj);

as mentioned in the comment i cannot use await on the async function call so i need the async function getById to wait for the data before returning what should i do

Amgad Serry
  • 1,595
  • 2
  • 12
  • 20

1 Answers1

1

i cannot use await on the async function call so i need the async function getById to wait for the data before returning

That's not what async functions do. As the name says, they are asynchronous, and they do return a promise for their result. They do not block and return synchronously. You have to wait, there's no way around it. Make the function with the calls async as well.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • well the function that calls it is the constructor of a class which cannot be set as async that's why i was looking for a work around ... what i did is that i made a factory function that creates new instances of that class and set it as async – Amgad Serry Sep 15 '16 at 20:35
  • @AmgadSerry Yes, [constructors shouldn't call async functions](http://stackoverflow.com/q/24398699/1048572) at all – Bergi Sep 15 '16 at 21:05
  • that is true it's much more cleaner to have an async factory function that actually instantiate objects of the class based on the given data – Amgad Serry Sep 15 '16 at 21:48