如何使WebSQL查询同步? [英] How to make a WebSQL query synchronous?

查看:161
本文介绍了如何使WebSQL查询同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

var globalvar;

function viewyearmain() {
  db.transaction(function (tx) 
  {
    tx.executeSql('SELECT * FROM BUDGET WHERE holdingtype="month"', [], function (tx, results) 
    {
       var len = results.rows.length;
       msg = len;
       globalvar = msg;
    }, null);

  });

  if (globalvar>0)
  {
    alert("ROWS FOUND");
  }
  else
  {
    alert("ROWS NOT FOUND");
  }
}

问题在于 ROWS未找到,因为到达 if 语句时交易尚未完成。

The problem is that ROWS NOT FOUND appears because the transaction has not completed by the time the if statement is reached.

推荐答案

异步回调不是同步的,无论你想要它多少。

An asynchronous callback is not synchronous, regardless of how much you want it to be.

只需移动所有代码取决于回调的结果:

Just move all the code the depends on the result into the callback:

var globalvar;

function viewyearmain() {
  db.transaction(function (tx) 
  {
    tx.executeSql('SELECT * FROM BUDGET WHERE holdingtype="month"', [], function (tx, results) 
    {
       var len = results.rows.length;
       msg = len;
       globalvar = msg;
       if (globalvar>0)
       {
         alert("ROWS FOUND");
       }
       else
       {
         alert("ROWS NOT FOUND");
       }
    }, null);

  });
}

或者,将其移至第二个函数,并从回调中调用它。

Alternatively, move it into a second function, and call that from the callback.

这篇关于如何使WebSQL查询同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆