我试图控制从端点获取某些数据的按钮的状态或状态,该端点的返回时间未知或可能超时。
我的按钮是典型的HTML <button>
,它使用onclick='doWork();'
我为默认状态(提交),单击(加载)和完成(完成)定义了类。
我必须使用此请求API(https://developers.freshsales.io/docs/request-api/)来调用我的端点。
请求API示例:
client.request.get("URL", options)
.then(
function(data) {
//handle "data"
//"data" is a json string with status, headers, and response.
},
function(error) {
//handle failure
}
);
方法
doWork();
function(data)
的承诺的回报,或返回交换类function(error)
样例代码:
function doWork(){
$('#btnSave').addClass('loading');
client.request.get("URL", options)
.then(
function(data) {
$('#btnSave').removeClass('loading');
$('#btnSave').addClass('completed');
// do other stuff
},
function(error) {
$('#btnSave').removeClass('loading');
$('#btnSave').addClass('failed');
// do some other stuff
}
);
}
问题
then()
返回后链接和处理按钮状态(在中处理状态)是否有任何优势.request.get.then().then(//Handle button state here)
?.catch()
防止用户陷入加载状态,还是通过某种超时来重置按钮更好地服务我?我仍然信守诺言,因此感谢能帮助我学习更多知识的见解。
您使用的方法很好,并且不需要链接,因为您只有一个异步调用。处理多个异步调用时,链接很有用。
至于第三个问题,我不明白您将在哪里使用catch,因为您的请求API(https://developers.freshsales.io/docs/request-api/)不支持它(至少不是根据文档)。您也可以在回调函数中处理请求超时,以解决以下错误:
function doWork(){
$('#btnSave').addClass('loading');
client.request.get("URL", options)
.then(
function(data) {
$('#btnSave').removeClass('loading');
$('#btnSave').addClass('completed');
// do other stuff
},
function(error) {
if(error.status == 504){
console.log('request timeout');
//do whatever you want
}
$('#btnSave').removeClass('loading');
$('#btnSave').addClass('failed');
// do some other stuff
}
);
}
另外,由于文档中提到的请求超时默认为“ 6秒”,因此您不会长时间处于加载状态。如果请求超时,则错误回调将处理错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句