Angular延迟实现仅输出循环的最后一个值

时间:2014-06-27 19:15:57

标签: javascript angularjs

我有一个自定义同步过程,我按顺序排队所有同步记录。当我的服务检索多个同步记录时,它将处理它们,然后更新每个成功记录的上一个同步日期,或者在失败时记录我的错误(不更新上一个同步日期)并中止同步过程。

我已经从AngularJS实施了$ q.all。这是同步循环的一个子集:

    var processes = [];

    for (var i in data) {
        if (data[i] === null || data[i].TableName == null || data[i].Query == null || data[i].Params == null) {
            // Let's throw an error here...
            throw new TypeError("ERROR! The data retrieved from the download sync process was of an unexpected type.");
        }

        var params = data[i].Params;
        var paramsMassaged = params.replaceAll("[", "").replaceAll("]", "").replaceAll(", ", ",").replaceAll("'", "");
        var paramsArray = paramsMassaged.split(",");

        mlog.Log("Query: " + data[i].Query);
        mlog.Log("Params: " + paramsArray);

        if (data[i].TableName === "table1") {
            var process = $table1_DBContext.ExecuteSyncItem(data[i].Query, paramsArray);

            process.then(
                function () {
                    $DBConfigurations_DBContext.UpdateLastSyncDate(data[i].CreatedDate, function (response) {
                        mlog.Log(response);
                    });
                },
                function (response) {
                    mlog.LogSync("Error syncing record: " + response, "ERROR", data[i].Id);
                },
                null
            );

            processes.push(process);
        } else if (data[i].TableName === "table2") {
            var process = $table2_DBContext.ExecuteSyncItem(data[i].Query, paramsArray);

            process.then(
                function () {
                    $DBConfigurations_DBContext.UpdateLastSyncDate(data[i].CreatedDate, function (response) {
                        mlog.Log(response);
                    });
                },
                function (response) {
                    mlog.LogSync("Error syncing record: " + response, "ERROR", data[i].Id);
                },
                null
            );

            processes.push(process);
        } else {
            mlog.LogSync("WARNING! This table is not included in the sync process. You have an outdated version of the application. Table: " + data[i].TableName);
        }
    }

    $q.all(processes)
        .then(function (result) {
            mlog.LogSync("---Finished syncing all records");
        }, function (response) {
            mlog.LogSync("Sync Failure - " + response, "ERROR");
        });

示例ExecuteSyncItem函数:

ExecuteSyncItem: function (script, params) {
    window.logger.logIt("In the table1 ExecuteSyncItem function...");

    var primaryKey = params[params.length - 1];

    var deferred = $q.defer();

    $DBService.ExecuteQuery(script, params,
        function (insertId, rowsAffected, rows) {
            window.logger.logIt("rowsAffected: " + rowsAffected.rowsAffected);

            if (rowsAffected.rowsAffected <= 1) {
                deferred.resolve();
            } else {
                deferred.resolve(errorMessage);
            }
        },
        function (tx, error) {
            deferred.reject("Failed to sync table1 record with primary key: " + primaryKey + "; Error: " + error.message);
        }
    );

    return deferred.promise;
}

我遇到的问题是,如果有多个同步记录失败,则此行显示所有失败记录的相同值(不确定它是否是第一个失败记录,或者最后一次)。

mlog.LogSync("Error syncing record: " + response, "ERROR", data[i].Id);

如何让它显示失败的特定记录的信息,而不是相同的消息&#34; x&#34;次?

2 个答案:

答案 0 :(得分:1)

comradburk所述,在循环中将进程封装在一个闭包中是一个很好的解决方案,但是有一种angular方法可以解决这个问题。您可以通过for-in执行此操作,而不是使用原生angular.forEach()循环,并循环遍历所有data元素。

var processes = [];

angular.forEach(data, function(item) {
    if (item === null || item.TableName == null || item.Query == null || item.Params == null) {
        // Let's throw an error here...
        throw new TypeError("ERROR! The data retrieved from the download sync process was of an unexpected type.");
    }

    var params = item.Params;
    var paramsMassaged = params.replaceAll("[", "").replaceAll("]", "").replaceAll(", ", ",").replaceAll("'", "");
    var paramsArray = paramsMassaged.split(",");

    mlog.Log("Query: " + item.Query);
    mlog.Log("Params: " + paramsArray);

    if (item.TableName === "table1") {
        var process = $table1_DBContext.ExecuteSyncItem(item.Query, paramsArray);

        process.then(
            function () {
                $DBConfigurations_DBContext.UpdateLastSyncDate(item.CreatedDate, function (response) {
                    mlog.Log(response);
                });
            },
            function (response) {
                mlog.LogSync("Error syncing record: " + response, "ERROR", item.Id);
            },
            null
        );

        processes.push(process);
    } else if (item.TableName === "table2") {
        var process = $table2_DBContext.ExecuteSyncItem(item.Query, paramsArray);

        process.then(
            function () {
                $DBConfigurations_DBContext.UpdateLastSyncDate(item.CreatedDate, function (response) {
                    mlog.Log(response);
                });
            },
            function (response) {
                mlog.LogSync("Error syncing record: " + response, "ERROR", item.Id);
            },
            null
        );

        processes.push(process);
    } else {
        mlog.LogSync("WARNING! This table is not included in the sync process. You have an outdated version of the application. Table: " + item.TableName);
    }
});

$q.all(processes)
    .then(function (result) {
        mlog.LogSync("---Finished syncing all records");
    }, function (response) {
        mlog.LogSync("Sync Failure - " + response, "ERROR");
    });

答案 1 :(得分:0)

问题是由于你对我的关闭。当回调函数执行时,i的值将是for循环中的最后一个值。您需要将该值绑定到一个单独的,不变的值。最简单的方法是使用自调用功能。

for (var i in data) {
    (function(item) {
        // Put your logic in here and use item instead of i, for example
        mlog.LogSync("Error syncing record: " + response, "ERROR", data[item].Id
    })(i);
}

这里有一个很好的解读为什么闭包会导致这个问题(这是一个非常常见的问题): Javascript infamous Loop issue?