-1

Hello I am creating an API and fetching data from rethinkdb for that I am using following code:

r.connect({
  host: 'localhost',
  port: 28015,
  db: 'test'
}, function (err, conn) {
  if (err) throw err;

  r.table('users').filter({email: user_data.name}).count().run(conn, (err, count) => {
    conn.close();
    if (err) {
      return res.status(404).send({ success: false });
    }
    else if (count == 0) {
      return res.status(401).send({ success: false });
    }
    return res.send({ success: true });
  });
});

But I need to create multiple API's and for that I don't want to repeat the connection code.

I want to create a common function to return rethinkdb connection.

I used following code:

global.con = r.connect({
    host: 'localhost',
    port: 28015,
    db: 'test'
});

and using con as connection object but it's giving error:

Unhandled rejection ReqlDriverError: First argument to run must be an open connection.

Using this:

 function findItem () {
   r.connect({
     host: 'localhost',
     port: 28015,
     db: 'test'
   }, function (err, conn) {
     if (err) throw err;

     return conn;
   });
 }

 global.c = findItem();

but still c is undefined

qzb
  • 8,163
  • 3
  • 21
  • 27
Ritu Gupta
  • 507
  • 2
  • 8
  • 22
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Oct 06 '16 at 07:03

2 Answers2

0

You cannot return anything from callback, asynchronous code doesn't work that way, you can check it by yourself:

function connect () {
  r.connect({ host: 'localhost', port: 28015, db: 'test' }, () => {
    console.log('callback called'); 
  });
}

connect();

console.log('connect function finished');

It will print this messages in reverse order, because callback is executed after rest of your code:

connect function finished
callback called

There are many solutions for this problem.

Also, using global and throwing exceptions from callback is rather bad idea. I strongly suggest to read more about how asynchronous programming works.

Community
  • 1
  • 1
qzb
  • 8,163
  • 3
  • 21
  • 27
  • when I use this r.table('users').filter({email: user_data.name}).count().run(connect(), (err, count) => { conn.close(); if (err) { return res.status(404).send({ success: false }); } else if (count == 0) { return res.status(401).send({ success: false }); } return res.send({ success: true }); }); it gives error : Unhandled rejection ReqlDriverError: First argument to `run` must be an open connection. – Ritu Gupta Oct 06 '16 at 09:16
0

I used following code..

app.use(function(req,res,next){
 r.connect({
    host: 'localhost',
    port: 28015,
    db: 'test'
 },function(err,conn){
    req['app_conn']=conn;
    next();
 });
});

and used req.app_conn as rethinkdb connection object

Ritu Gupta
  • 507
  • 2
  • 8
  • 22