Returning data from a PouchDB query

无人久伴 提交于 2021-01-28 08:09:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32400079/returning-data-from-a-pouchdb-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!