Невозможно вернуть значение из обратного вызова nano.view - PullRequest
0 голосов
/ 30 июня 2019

Невозможно сохранить значение вне области обратного вызова

Я попытался объявить массив, объект и пустую переменную вне области обратного вызова, и ничего не работает.

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")
  }
})

Я получаю вывод "undefined"

1 Ответ

1 голос
/ 01 июля 2019

Проблема в том, что вы пытаетесь использовать обратный вызов + обещания.Вам нужно либо выбрать одно, либо другое.

Вот реализация с использованием Promises (с 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")
  }
})
...