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.