我正在创建一个React应用程序,其中涉及对一些Webapi REST服务的多次调用来完成我的任务。该应用程序的一部分是一些请求的批准流程。有一个特定的角色可以使用包含以下内容的UI创建这些流:
该表列出了按基数(即顺序)排序的过程步骤。这些步骤还具有参与者和状态。
每行上的按钮用于上/下排列
每行上的按钮可删除相应行
用于添加新步骤的按钮。
我要做的是允许用户使用Javascript(主要是数组操作)进行更改,同时用操作和相应数据填充操作缓冲区数组。例如。
this.actionsBuffer.push({
action: "ADD_STEP",
data: next
});
当用户对布置感到满意时,她可以按下“接受”按钮。它的作用是迭代actionsBuffer数组并执行由action字段确定的适当的REST服务。
我知道我的描述似乎太详细了,但我想让你知道背景。
题:
现在我的问题是,由于调用是异步的,我如何保证操作将按此顺序执行。
一些代码片段:
这会迭代并调用defineAction
onAccept: function (e) {
e.preventDefault();
var self = this;
//console.log("Gonna save:",JSON.stringify(this.state.workflow));
var ret=null;
// First we do actions in actionsBuffer
for(var i=0;i<this.actionsBuffer.length;i++)
{
ret = self.determineAction(this.actionsBuffer[i]);
if (ret==false)
break;
else
this.actionsBuffer.splice(i,1);
ret=null;
}
this.saveAll();
},
并确定动作。原谅调试控制台消息
determineAction: function (action) {
var url="";
var verb="";
switch(action.action)
{
case "ADD_STEP":
delete action.data.ActorList;
url=this.props.server+"/workflows/"+this.props.workflowid+"/steps";
verb="POST";
break;
case "DELETE_STEP":
url=this.props.server+"/workflows/"+this.props.workflowid+"/delete/";
verb="POST";
break;
}
console.log("Going to call url:",url," with varb:",verb," and data:",action.data);
$.ajax({
type: verb,
url: url,
data: JSON.stringify(action.data),
processData:false,
contentType: 'application/json'
})
.success(function(data) {
return true;
//self.props.onclose(self.state.workflows.WorkflowId);
})
.error(function(jqXhr) {
console.log(jqXhr);
return false;
});
},
最佳答案
您不是在等待determineAction
完成。使它返回一个承诺,并在调用它的地方等待。同样,您的循环必须是异步的。我创建的尝试可能并不完全符合您的需要,但会向您显示应该移动的方向。
onAccept: function (e) {
e.preventDefault();
var self = this;
var ret=null;
// First we do actions in actionsBuffer
var i = 0;
function makeRequest() {
self.determineAction(self.actionsBuffer[i]).success(function() {
i++;
if (i >= (self.actionsBuffer.length) {
self.saveAll();
} else {
makeRequest();
}
}).error(function(){
self.saveAll();
})
}
makeRequest()
this.saveAll();
},
determineAction: function (action) {
var url="";
var verb="";
switch(action.action)
{
case "ADD_STEP":
delete action.data.ActorList;
url=this.props.server+"/workflows/"+this.props.workflowid+"/steps";
verb="POST";
break;
case "DELETE_STEP":
url=this.props.server+"/workflows/"+this.props.workflowid+"/delete/";
verb="POST";
break;
}
console.log("Going to call url:",url," with varb:",verb," and data:",action.data);
return $.ajax({
type: verb,
url: url,
data: JSON.stringify(action.data),
processData:false,
contentType: 'application/json'
});
},