简体   繁体   English

代码未按顺序执行

[英]Code not executed in sequence

I have a document in my cloudant db with _id of mittens13 . 我的cloudant数据库中有一个带有_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. 但是,查询语句之外的那个首先被调用,它给出了一个undefined警报,然后它给了另一个警告hello ,这是doc中的项目。 May I know why? 我可以知道为什么吗?

Javascript code Javascript代码

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 我的数据库中的doc的详细信息

{
  "_id": "mittens13",
  "_rev": "1-78ef016a3534df0764bbf7178c35ea11",
  "title": "hello",
  "occupation": "kitten123"
}

Question: Why is alert(price); 问题:为什么alert(price); producing undefined ? 生产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. 您的alert(price)显示未定义的原因,即使代码是在db.get代码之后编写的,因为db.get是异步的。

Because it is an asynchronous call, your program will not wait for the response of db.get before it continues. 因为它是异步调用,所以程序在继续之前不会等待db.get的响应。 So before your db.get comes back, your program has already reached the alert(price); 所以在你的db.get回来之前,你的程序已经达到了alert(price); line. 线。 It looks and sees that the only other code that has been written regarding price is var price; 它看起来并且看到关于价格的唯一其他代码是var price; . Which, if you tried to print, would result in undefined. 如果您尝试打印,则会导致未定义。

You should research ajax and callbacks. 你应该研究ajax和回调。

db.get is asyncronous, so when alert(price) is called the function before it is actually still running (on a different thread). db.get是异步的,所以在调用alert(price)之前,函数实际上仍在运行(在不同的线程上)。 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). .then允许警报(价格)仅在上一个任务完成后运行,它也在同一个线程上运行(我相信,有人可能会纠正我)。 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) 你也应该添加一些错误检查,如果你发现错误,请务必取消任务继续(.then)

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

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