How to use async and await in NodeJs

0

I'm trying to learn how to use async await but, I'm missing something and 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 console.log normally the data I need arrives; the class / method it provides 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 turn this using async and await then I tried but it 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 return it turns a promise, until then ok ... But when I receive it only returns me undefined.

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

I do not know where I'm going wrong. I'll be grateful for your help.

    
asked by anonymous 17.07.2018 / 21:37

1 answer

1

The error is that you do not have to tinker with openConnection. To use async / await, the calling function must return a Promise. See Mozilla reference. So your code should be:

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 the open connection everything remains normal, and the change would only be in getMainPage which 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 reject in Promise, to be able to let the error in the function that is calling, making the code more "decoupled".

    
17.07.2018 / 22:44