简体   繁体   中英

Returning data from a PouchDB query

I'm having a problem returning data from a PouchDB query. I'm trying to build a function that, when called, returns specific data from a 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". The return value of that asynchronous function needs to be returned in a callback or a promise.

If "pouch.get" returns a promise, as you are showing above with the ".then" you can write your code like this:

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. See an example in their docs here . Therefore, this code will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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