1

I have a document in my cloudant db with _id of mittens13. I tried to query it and alert, one in the query statement and another one outside the query statement.

However, the one outside the query statement were called first and it gave an alert of undefined and then it gave another alert hello which was the item in the doc. May I know why?

Javascript code

function queryDB() {

    var price;

    db.get("mittens13", function (err, response) {
        console.log(err || response);
        alert(response.title);
        price = response.title;
    });

    alert(price);
}

Details of the doc in my db

{
  "_id": "mittens13",
  "_rev": "1-78ef016a3534df0764bbf7178c35ea11",
  "title": "hello",
  "occupation": "kitten123"
}
Community
  • 1
  • 1
Alvin
  • 408
  • 3
  • 14
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Aug 04 '16 at 14:39

2 Answers2

2

Question: Why is alert(price); producing undefined?

The reason why your alert(price)shows undefined, even though the code is written after your db.get code, is because db.get is asynchronous.

Because it is an asynchronous call, your program will not wait for the response of db.get before it continues. So before your db.get comes back, your program has already reached the alert(price); line. It looks and sees that the only other code that has been written regarding price is var price;. Which, if you tried to print, would result in undefined.

You should research ajax and callbacks.

Chris Newman
  • 3,152
  • 1
  • 16
  • 17
1

db.get is asyncronous, so when alert(price) is called the function before it is actually still running (on a different thread). I think the correct way would be:

db.get("mittens13", function (err, response) {
    console.log(err || response);
    alert(response.title);
    price = response.title;
}).then(function(){ alert(price) };

the .then allows the alert(price) to run only after the previous task as finished, it also runs on the same thread (i believe, somebody will probably correct me). also a small side note, you should probably add some error checking and if you catach an error be sure to cancel the task continuation (.then)

user3164339
  • 165
  • 14