【问题标题】:Code not executed in sequence代码未按顺序执行
【发布时间】:2016-08-04 14:39:11
【问题描述】:

我的 cloudant 数据库中有一个文档,其中包含 _idmittens13。我试图查询它并发出警报,一个在查询语句中,另一个在查询语句之外。

但是,首先调用了查询语句之外的那个,它给出了undefined 的警报,然后它给出了另一个警报hello,这是文档中的项目。我可以知道为什么吗?

Javascript 代码

function queryDB() {

    var price;

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

    alert(price);
}

我的数据库中文档的详细信息

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

【问题讨论】:

标签: javascript sql pouchdb cloudant nosql


【解决方案1】:

问题:为什么alert(price); 产生undefined

您的alert(price) 显示未定义的原因是因为db.get 是异步的,即使代码是在您的db.get 代码之后编写的。

因为是异步调用,所以你的程序不会等待db.get的响应才继续。所以在你的db.get 回来之前,你的程序已经到达alert(price); 行。它看起来并看到关于价格的唯一其他代码是var price;。如果您尝试打印,则会导致未定义。

您应该研究 ajax 和回调。

【讨论】:

    【解决方案2】:

    db.get 是异步的,因此当调用 alert(price) 时,该函数实际上仍在运行(在不同的线程上)。我认为正确的方法是:

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

    .then 允许警报(价格)仅在上一个任务完成后运行,它也在同一个线程上运行(我相信,有人可能会纠正我)。还有一个小说明,您可能应该添加一些错误检查,如果您发现错误,请务必取消任务继续 (.then)

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      相关资源
      最近更新 更多