Sum_Pie
Sum_Pie

Reputation: 185

rethinkdb & nodejs: save result in var

it's possible save result query of rethinkdb in a variable?

Like this??

var test = r.db('chat').table('group_chat').count(r.row('passengers').contains(function(passeggers) {
   return passeggers('nome').eq('pigi');
 })).run()

now I use this method

var test;

r.db('chat').table('group_chat').count(r.row('passengers').contains(function(passeggers) {
   return passeggers('nome').eq('pigi');
 })).run().then(function(response){
    test = response;
})

Upvotes: 1

Views: 92

Answers (2)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Simplest yet working solution would be as bellow, using callback

function getTest(callback) { // add callback
    r.db('chat')
     .table('group_chat')
     .count(r.row('passengers')) // you forgot closing brace here
     .contains(function(passeggers) { 
       return passeggers('nome').eq('pigi') 
     })
     .run()
     .then(function(result) {
       callback(null, result); // call callback with result
     })
     .error(function(err) {
       callback(err, null);  // call callback with error
     });
}

getTest(function(err, result) { // invoke callback
  if (err) throw err;

  console.log(result)
  var test = result; // note: you can use test variable only inside this call
})

Upvotes: 0

Patrick Hund
Patrick Hund

Reputation: 20236

If you don't like using promises and are using the latest version of ECMAScript, you can use async/await, which provides syntactic sugar to let you write your asynchronous code as if it were synchronous.

You could rewrite your example like this:

async function getTest() {
    var test = await r.db('chat').table('group_chat').count(r.row('passengers').contains(function(passeggers) {
        return passeggers('nome').eq('pigi');
    })).run();
    return test;
}

Note that “behind the scenes”, this still uses promises, but it makes the code easier to read and understand.

Upvotes: 0

Related Questions