简体   繁体   English

从PouchDB查询返回数据

[英]Returning data from a PouchDB query

I'm having a problem returning data from a PouchDB query. 我从PouchDB查询返回数据时遇到问题。 I'm trying to build a function that, when called, returns specific data from a PouchDB. 我正在尝试构建一个函数,该函数在调用时从PouchDB返回特定数据。 Here is my code: 这是我的代码:

function getUserFullName() {
            var db = "userInfo";
            var pouch = new PouchDB(db);
            pouch.get("token").then(function (result) {
            console.log(result-user_real_name);
                return result.user_real_name;
            }).catch(function (error) {
                console.log(error);
            });
        }

So what happens is that the function returns an undefined. 所以发生的是该函数返回一个未定义的。 Does anyone have a clue as to what I'm doing wrong? 有人知道我在做什么错吗?

The issue is that it looks likes you are running "getUserFullName" synchronously, but you have an asynchronous function inside of it, "pouch.get". 问题是,看起来您正在同步运行“ getUserFullName”,但是其中具有异步功能“ pouch.get”。 The return value of that asynchronous function needs to be returned in a callback or a promise. 该异步函数的返回值需要在回调或Promise中返回。

If "pouch.get" returns a promise, as you are showing above with the ".then" you can write your code like this: 如果“ pouch.get”返回一个promise,如上面显示的“ .then”所示,则可以这样编写代码:

function getUserFullName() {
  var db = "userInfo";
  var pouch = new PouchDB(db);

  return pouch.get("token")
}

And run it like this: 并像这样运行它:

getUserFullName()
  .then(function(fullUserName){
    console.log(fullUserName);
  })
  .catch(function(err){
    console.log(err);
  });

Let me know if that works, or if you have any questions. 让我知道这是否可行,或者您有任何疑问。 Thanks! 谢谢!

EDIT: Looks like "pouch.get" does return a promise. 编辑:看起来“ pouch.get”确实返回了一个承诺。 See an example in their docs here . 此处查看其文档中的示例。 Therefore, this code will work. 因此,此代码将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM