0

I have the below code which tries to connect to MongoDB queries for some data and returns the results, but my code trying to print the result before the MongoDB query completes. How can i convert the below code to wait for the query to complete then proceed with printing the results.

Tried researching about Promise, async/await, but this practical example would help to understand the promise, async/await

const getTicks = () => {
    TicksModel.find().select({tick:1,_id:0})
    .then(results => {
        return results;
    }).catch( err => {  
        //TODO - generate alert
        console.error(err);
    })
}

const ticks = getTicks();
console.log(ticks);

Expected: wait for MongoDB query to complete then console log ticks

veeRN
  • 143
  • 1
  • 1
  • 9
  • what is the node version you are using? Try using async await – VariableVasasMT Apr 07 '19 at 01:47
  • V 11.11 , tried converting to async await but not working, could you convert this to async await – veeRN Apr 07 '19 at 01:49
  • 2
    `const getTicks = () => TicksModel.find().select({tick:1,_id:0})` and then `getTicks().then(result => console.log(result)).catch(err => console.error(err))` The function returns a `Promise` and nothing you can do will actually *change* that. The async response comes from the function and cannot be *"converted to synchronous"* within the function. – Neil Lunn Apr 07 '19 at 01:52
  • 2
    Or `const getTicks = () => TicksModel.find().select({tick:1,_id:0})` and then `try { let result = await getTicks(); } catch(e) { console.error(e) }` But you **must** be within a block declared as `async` in order to `await`. Note this is all stated in the linked answers. – Neil Lunn Apr 07 '19 at 01:54
  • `const getTicks = async () => { try { return TicksModel.find().select({tick:1,_id:0}); } catch(e) { console.error(e); } } const ticks = await getTicks(); console.log(ticks);` – VariableVasasMT May 17 '19 at 14:18

0 Answers0