A value which executes an function returns a promise

Viewed 44

I have this piece of code and in the 2nd function where i check the db if i log stuff inside the function it logs fine but if i assign a var and call the function as it returns a true of false i get a pending promise

const mongoose = require('mongoose')
const config = require('./config.json')
const schema = require('./data')
const mongoactivate = async(config) => {
  await mongoose.connect(config.mongo, {
    useUnifiedTopology: true,
    useNewUrlParser: true
  })
}
mongoactivate(config)
const check = async(p, q) => {
  let data = await schema.findOne({
    username: p,
    pass: q
  })
  let cor = (data === null) ? false : true;
  console.log(cor)
}
const ans = check("p", "q")
console.log(ans)
3 Answers

You are in troubles with async/await. You have to await first mongoactivate(config) and check('p', 'q'). Try writing await before those functions.

Good luck my g

You're not awaiting the mongoactivate() function. Async functions always return a Promise. Also, your check function never returns anything, so ans won't be the value you'd expect it to be. Return the cor variable at the end of the function.

const mongoose = require('mongoose')
const config = require('./config.json')
const schema = require('./data')

const mongoactivate = async (config) => {
  await mongoose.connect(config.mongo, {
    useUnifiedTopology: true,
    useNewUrlParser: true
  })
}

const check = async (p, q) => {
  let data = await schema.findOne({
    username: p,
    pass: q
  })
  let cor = (data === null) ? false : true;
  return cor;
}

(async () => {
  await mongoactivate(config)
  const ans = await check("p", "q")
  console.log(ans)
})()

you need to know how to work with await/async , JS is not like C# or C if you still have some issues with that i advice you to resolve the promise like in this exemple :

 const Afunction = async(p,q)=> {
 let ThePromise = new Promise((resolve,reject) => {
      //resolve the pending promise that you got
         let data = await schema.findOne({
         username: p,
         pass: q
         })
       let cor = (data === null) ? false : true; 
       resolve(cor)
 })
return ThePromise.then(val=> {return val} )
}

And then you can get the result with:

  const TheValueIwant = await Afunction ("p","q");
Related