【问题标题】:detect when asynchronus tasks is done [duplicate]检测异步任务何时完成[重复]
【发布时间】:2014-03-27 08:04:12
【问题描述】:

我想检测这个异步操作列表何时完全完成,以及在其他操作中使用插入的条目。

    var peers = this.response["peers"];
    $.each(peers, function(key, value) {
        that.database.transaction(function(tx) {
            var user_id = parseInt(value["user_id"]);
            var username = value["username"];
            var picture = value["picture"];
            var date_of_birth = value["date_of_birth"];
            var score = parseInt(value["score"]);
            var country = value["country"];
            var last_seen = value["last_seen"];
            var is_favorite = value["is_favorite"];
            var is_match = value["is_match"];
            var is_blocked = value["is_blocked"];
            var is_auto_match = value["is_auto_match"];
            var is_profile_viewer = value["is_profile_viewer"];
            var sql = "insert into users(user_id,username,picture,";
            sql += "date_of_birth,score,country,last_seen,is_blocked,";
            sql += "is_favorite,is_match,is_auto_match,is_profile_viewer)";
            sql += "values (?,?,?,?,?,?,?,?,?,?,?,?)";
            tx.executeSql(sql, [user_id, username, picture, date_of_birth, score, country, last_seen, is_blocked, is_favorite, is_match, is_auto_match, is_profile_viewer]);
        });
    });

【问题讨论】:

  • 您是否使用任何异步库,例如 asyncq
  • 不,我不使用任何异步库,但 sqlite 事务是一种异步方法
  • 该循环中有多个调用需要回调。您应该考虑使用 jQuery 的 promise
  • 其实我没有用jquery,我用的是手机appframework
  • 该死的...$.each 看起来很眼熟。你确定它不是 jQuery 吗?你仍然应该使用 promise 库,它使代码组织更容易。

标签: javascript sqlite asynchronous


【解决方案1】:

如果你不能使用任何异步技术,那么你可以这样做

var peers = this.response["peers"];
var total = peers.length;
$.each(peers, function(key, value) {
    that.database.transaction(function(tx) {
        ...
        tx.executeSql(sql, [...], function() {
            total -= 1;
            if (!total) {
                otherOperation(...); // Invoke the operation after all data done
            }
        });
    });
});

【讨论】:

    猜你喜欢
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多