How to use async and await in Nodejs

Asked

Viewed 335 times

0

I am trying to learn how to use async await but, I am missing something and I need help. My method works as expected with Promise see:

import express from 'express';
import conn from '../models/connection';
const c =  conn;

class ClientRoutes {
...
    getMainPage(req, res, next) {
        c.openConection().then((a) => {
            console.log(a);
            res.render('index', {title: 'Abner'})
        })           
    }
...

when I see through the.log console comes normally the data I need; the class/method you provide is:

import r from 'rethinkdb';

class Db_Conection {

    openConection(req, res, next) {
        return new Promise((resolve) => {
            r.connect({host: process.env.DB_HOST, port: process.env.DB_PORT}, (err, conn) => {
                if ( err && err.name === 'ReqlDriverError' && err.message.indexOf( 'Could not connect' ) === 0 && ++count < 3 ) {
                    console.log( err );
                    return;                
                }
                resolve(conn);            
            })
        })
    }
...

I want to transform it using async and await hence tried but went wrong the following:

...
    async openConection(req, res, next) {
        r.connect({host: process.env.DB_HOST, port: process.env.DB_PORT}, (err, conn) => {
            if ( err && err.name === 'ReqlDriverError' && err.message.indexOf( 'Could not connect' ) === 0 && ++count < 3 ) {
                console.log( err );
                return;                
            }
            return conn;            
        })
    }
...

Above the returns becomes a Promise, until then ok... But when I will receive only returns Undefined.

...
    async getMainPage(req, res, next) {
        const b = await c.openConection();
        console.log(b);
        // res.render('index', {title: 'Abner'})
    }
...

I don’t know where I’m going wrong. I’ll be grateful for your help.

1 answer

1


The error is that you do not need to touch openConnection. To use async/await, the called function must return a Promise. See the reference of Mozilla. So your code should stay:

openConection(req, res, next) {
    return new Promise((resolve, reject) => {
        r.connect({host: process.env.DB_HOST, port: process.env.DB_PORT}, (err, conn) => {
            if(err)
                 return reject(err)
            resolve(conn);            
        })
    })
}

In open Connection everything remains normal, and the change would only be in getMainPage that becomes:

async getMainPage(req, res, next) {
    try {
        const b = await c.openConnection();
        console.log(b);
        res.render('index', {title: 'Abner'})
    } catch (error) {
        // Caso a promise seja rejeitada, trata o erro
        console.error(error)
        res.status(500).json({mgs: "Um erro ocorreu"})
    }
}

Just an addendum, I had the freedom to use Retject in Promise, to be able to treat the error in the function that is calling, making the code more "uncoupled".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.