Natasha Kelly
Natasha Kelly

Reputation: 73

Unable to return value from nano.view callback

Unable to store value outside of callback scope

I have tried declaring an array, an object and an empty variable outside of the callback scope and nothing is working.

router.post('/login', async (req, res, next) => {
  try {
    const user = await users.view('viewEmailandPassword', 'email', {keys: [`${req.body.email}`], include_docs: true},
       function(err, body) {
          if (!err) {
            body.rows.forEach(function(doc) {
              console.log(doc.value)
              // return doc.value
            });
          }
        });
        console.log(user) <--- nothing is returned
  }
  catch(err){
    next(err)
    console.err(err, "this is the error")
  }
})

I get an output of "undefined"

Upvotes: 0

Views: 76

Answers (1)

Alexis C&#244;t&#233;
Alexis C&#244;t&#233;

Reputation: 3690

The problem here is that you're trying to use callback + promises. You need to either choose one or the other.

Here's the implementation using Promises (with async/await)

router.post('/login', async (req, res, next) => {
  try {

    const body = await users.view('viewEmailandPassword', 'email', {keys: [`${req.body.email}`], include_docs: true});

    // Prints all the row values
    body.rows.forEach(doc => console.log(doc.value));

    // Let's say you want the first row
    if(body.rows.length > 0){
        console.log(body.rows[0].value);
    } else {
        console.log("Not value returned from the view");
    }
  }
  catch(err){
    next(err)
    console.err(err, "this is the error")
  }
})

Upvotes: 1

Related Questions