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.
Thank you very much.
– Abner Passos Magalhaes