1

为了读取下面显示的表脚本,我尝试在参数中运行查询,并为每个结果尝试将不同表中的值附加到结果中。但是由于 azure 的异步特性,request.respond() 总是在 getInvites 之前调用。这意味着结果永远不会附加邀请。

function read(query, user, request) {

    request.execute({
        success: function (results) {
            for (var i = 0; i < results.length; i++) {
                getInvites(results[i].id, function (invites) {
                    console.log("Assigning results.invites"); //runs second
                    results[i].invites = invites;
                });
            }
            console.log("Request Responding"); //runs first
            request.respond();
        }
    });

}

function getInvites(id, cb) {
    var InvitesTable = tables.getTable("Invites").where({
        "PlanID": id
    }).select("UserID", "Attending");
    InvitesTable.read({
        success: function (results) {
            if (cb) cb(results);
        }
    });
}

是一个后续问题,因为我无法在 Azure 中使用外部库。那么我该如何解决这个问题呢?

4

2 回答 2

4

操作的异步性质使得这有点挑战。您需要做的是仅request.respond()在所有操作完成后才调用。我真的很怀念await我在 C# 中非常喜欢的关键字,但我以前使用过“异步 for 循环”,而且效果很好。您的代码如下所示:

function read(query, user, request) {
    request.execute({
        success: function (results) {
            var index = 0;
            var executeStep = function() {
                if (index === results.length) {
                    // all invites have been retrieved
                    console.log("Request Responding");
                    request.respond();
                } else {
                    getInvites(results[index].id, function(invites) {
                        console.log('Assigning results.invites');
                        results[i].invites = invites;
                        index++;
                        executeStep();
                    });
                }
            }

            executeStep();
        }
    });
}

function getInvites(id, cb) {
    var InvitesTable = tables.getTable("Invites").where({
        "PlanID": id
    }).select("UserID", "Attending");
    InvitesTable.read({
        success: function (results) {
            if (cb) cb(results);
        }
    });
}
于 2013-01-17T03:33:38.953 回答
0

好的,你可能会做这样的事情

function read(query, user, request) {

    request.execute({
        success: function (results) {
            for (var i = 0, len = results.length; i < len; i++) {
                getInvites(results.id, function (invites) {
                    console.log("Assigning results.invites"); //runs second
                    results.invites = invites;

                    if (i === len-1) request.respond();
                });
            }
            console.log("Request Responding"); //runs first
        }
    });

}

function getInvites(id, cb) {
    var InvitesTable = tables.getTable("Invites").where({
        "PlanID": id
    }).select("UserID", "Attending");
    InvitesTable.read({
        success: function (results) {
            if (cb) cb(results);
        }
    });
}

它基本上意味着request.respond()将在您最后一次迭代的成功回调时调用。

于 2013-01-16T15:21:49.630 回答