【问题标题】:Unable to return value from nano.view callback无法从 nano.view 回调返回值
【发布时间】:2019-07-02 04:23:31
【问题描述】:

无法在回调范围之外存储值

我尝试在回调范围之外声明一个数组、一个对象和一个空变量,但没有任何效果。

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

我得到“未定义”的输出

【问题讨论】:

    标签: callback couchdb couchdb-nano


    【解决方案1】:

    这里的问题是您正在尝试使用回调 + 承诺。您需要选择其中一个。

    这是使用 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")
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2016-01-07
      • 2012-03-27
      • 1970-01-01
      • 2013-04-22
      • 2021-06-10
      • 1970-01-01
      • 2021-08-23
      相关资源
      最近更新 更多