Search code examples
javascriptnode.jsexpressasynchronousnode-postgres

How can I make sure my promise from postgres gets resolved before proceding?


Im making a Node-js app which needs to look up some info from the database before proceeding with another db-call, but I cant seem to make sure that the first check is resolved before proceeding. How can I make sure that the first query is always fulfilled before proceeding? I've tried nesting .next, but they seem to be skipping anyway. So after the first DB-call I want to check the returned value, but its always undefined.

my async function:

async function GetStuff(text, id){
  try {
    return await db.query(text, id);
   } catch(error) {
      console.log('fel inne: ' + error)
      logger.error('Fel: ' + error)
    return null;
  }
}

My Controller-code where I call the method and then try await the call with .next.

router.post('/newStuff', async (req, res) => {

    //Check if number exist in DB
    const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
    const values = [req.body.from];

    GetStuff(checkUserText, values)
    .then(function(result) {
        var user = result.rows[0];

        //HERE I GET UNDEFINED for some reason. I need to check the result in order to select the next step.
        if(user.userid !== null){
            console.log(user)

        //do some stuff...

        } else {
            res.end('Not OK')
        }
    }).catch(function(error) {
        console.log('fel: ' + error)
        logger.error('Fel: ' + error)
        res.end('Error')
    });
})

Solution

  • Instead of returning null from GetStuff, you should probably throw either the original error or a new error. This will then cause GetStuff.catch to be triggered if something goes wrong with the database call.

    Just a tip as well, your controller function is async so you don't need to use Promise based structure in your controller code. You can also use async/await.

    With both of those, you'd end up with the following code:

    async function GetStuff(text, id){
        try {
            return await db.query(text, id);
        } catch(error) {
            console.log('fel inne: ' + error)
            logger.error('Fel: ' + error)
    
            throw new Error('Failed to get db record');
        }
    }
    
    router.post('/newStuff', async (req, res) => {
        //Check if number exist in DB
        const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
        const values = [req.body.from];
    
        let dbResult;
        try {
            dbResult = await GetStuff(checkUserText, values);
        } catch (err) {
            console.log('fel: ' + error)
            logger.error('Fel: ' + error)
            res.sendStatus(500);
        }
    
        const user = dbResult.rows[0];
    
        if (user.userid !== null) {
            console.log(user);
        }
    
        // Do some more things...
    
        res.sendStatus(200); // All good!
    }