为了读取下面所示的表脚本,我尝试在参数中运行查询,并针对每个结果尝试将不同表中的值附加到结果中。但由于 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);
}
});
}
这是 this 的后续问题因为我无法在 Azure 中使用外部库。那么我该如何解决这个问题呢?
最佳答案
操作的异步性质使得这有点具有挑战性。您需要做的是仅在所有操作完成后调用 request.respond()
。我真的很怀念 C# 中我非常喜欢的 await
关键字,但我以前使用过“异步 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);
}
});
}
关于javascript - 在 Azure 中处理多个异步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14360605/