角色服务
this.sendCommand = function (someData) {
URL = myURL;
return $http({
method: 'POST',
url: URL,
data: someData
}).then(function (response) {
return response.data;
}).catch(function (error) {
console.log(error)
});
};
使用案例:用户可以通过单击按钮发送多个命令。例如,在满足请求1响应之前,请求2不应返回响应。如何使用上面的代码片段进行同步调用,这样即使用户多次点击某个按钮,发送的请求也会在队列中提供?
答案 0 :(得分:0)
我认为使用布尔变量可以更好地处理它。由于javascript是单线程的,你可以创建一个变量'isWaitingForResponse'并添加一个if只有在没有其他进行中才发送请求。
this.sendCommand = function (someData) {
if (!this.isWaitingForResponse) {
this.isWaitingForResponse = true;
// do request
.then(
this.isWaitingForResponse = false;
);
} else {
// don't send request
}
};
如果您真的想要排队请求,可以使用javascript:queue stackoverflow queue question。然后你的代码看起来像这样:
this.sendCommand = function (someData) {
if (!this.isWaitingForResponse) {
this.isWaitingForResponse = true;
// do request
.then(
this.isWaitingForResponse = false;
// check if there is a request in a queue
// if there is: invoke this.sendCommand
);
} else {
// don't send request
// put request in a queue
}
};
答案 1 :(得分:0)
您可以使用微调器阻止用户在上一个请求完成之前单击该按钮。