[英]JavaScript await for AJAX before continuing
在使用 kendo ui 的內聯網格編輯上單擊更新時,我遇到了競爭條件。
在保存時,我在保存時執行以下功能:
dataBound: function (e) {
// This needs to run after the save has finished
},
save: function (e) {
$.when(
$.ajax({
type: "GET",
url: "/Admin/OperatingCentre/GetById?id=" + e.model.OperatingCentreId,
success: function (data) {
e.model.OperatingCentreName = data.Name;
}
}),
$.ajax({
type: "GET",
url: "/Admin/Division/GetById?id=" + e.model.DivisionId,
success: function (data) {
e.model.DivisionName = data.Name;
}
}),
$.ajax({
type: "GET",
url: "/Admin/OperatingCompany/GetById?id=" + e.model.OperatingCompanyId,
success: function (data) {
e.model.OperatingCompanyName = data.Name;
}
})
);
}
我所追求的是等待 $.when 函數,因為網格不會等待它調用數據綁定,因此 e.model.OperatingCentreName 等沒有及時設置以顯示在網格中。
添加 await 這也無濟於事:
save: async function (e) {
await $.when(
任何建議將不勝感激。
dataBound: function(e) { // This needs to run after the save has finished }, save: function(e) { $.when( $.ajax({ type: "GET", url: "/Admin/OperatingCentre/GetById?id=" + e.model.OperatingCentreId, success: function(data) { e.model.OperatingCentreName = data.Name; } }), $.ajax({ type: "GET", url: "/Admin/Division/GetById?id=" + e.model.DivisionId, success: function(data) { e.model.DivisionName = data.Name; } }), $.ajax({ type: "GET", url: "/Admin/OperatingCompany/GetById?id=" + e.model.OperatingCompanyId, success: function(data) { e.model.OperatingCompanyName = data.Name; } }) ).done(function(a1, a2, a3) { // a1, a2, and a3 are arguments resolved for the each of the ajax requests, respectively. // Each argument is an array with the following structure: //[ data, statusText, jqXHR ] // here trigger the dataBound }); }
我相信async/await
應該可以解決您的問題
save: async function (e) {
await $.ajax({
type: "GET",
url: "/Admin/OperatingCentre/GetById?id=" + e.model.OperatingCentreId,
success: function (data) {
e.model.OperatingCentreName = data.Name;
}
}),
await $.ajax({
type: "GET",
url: "/Admin/Division/GetById?id=" + e.model.DivisionId,
success: function (data) {
e.model.DivisionName = data.Name;
}
}),
await $.ajax({
type: "GET",
url: "/Admin/OperatingCompany/GetById?id=" + e.model.OperatingCompanyId,
success: function (data) {
e.model.OperatingCompanyName = data.Name;
}
})}
通過這種方式,您將阻止腳本的執行,直到執行 ajax 調用並執行成功回調
添加。 保存功能中的異步
save: async function (e) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.