简体   繁体   中英

JavaScript pouchDb single doc data retrieval

I'm fairly new to JavaScript and I can't seem to find the answer to this anywhere.

I want to retrieve the JSON returned by a pouchDb get() and be able to use that data outside of the promise function used when querying the db.

Here is what I have/have tried so far:

 var row; db.get(id) .then(function(doc){ row = JSON.parse(JSON.stringify(doc)); }) .catch(function(err){ console.log(err) }) console.log(row) //logs undefined 

I also randomly for some reason tried this and got unexpected results.

 var myArray = [] var row; db.get(id) .then(function(doc){ row = JSON.parse(JSON.stringify(doc)); myArray.push(row) console.log(myArray) //logs Array(1)> 0: Object> my JSON! console.log(myArray[0]) //logs Object > my JSON! console.log(myArray[0]._id) //logs My id from my db item }) .catch(function(err){ console.log(err) }) console.log(myArray) //logs Array(1) > 0: Object > my JSON! console.log(myArray[0]) //logs undefined console.log(myArray[0]._id) //throws Uncaught TypeError: Cannot read property '_id' of undefined + wall of red text 

I hope this makes sense--also I may be fundamentally misunderstanding how javascript works.

You can't use the result of the "get" database call outside the promise in the way you have it in your code. That's because the console.log line is being executed in your program before the database has a chance to respond. If you put the console.log line inside the promise result it should work...

 var row; db.get(id) .then(function(doc){ row = JSON.parse(JSON.stringify(doc)); console.log(row) //should now work }) .catch(function(err){ console.log(err) }) 

You could, for example, call another function from within your promise result, or you can chain promises together if you need to do one thing after another. Nolan Lawson's article "We Have A Problem With Promises" looks at this and is worth a read.

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