实现某些异步函数超时是一种常见模式,使用deffered/promise:
// Create a Deferred and return its Promise
function timeout(funct, args, time) {
var dfd = new jQuery.Deferred();
// execute asynchronous code
funct.apply(null, args);
// When the asynchronous code is completed, resolve the Deferred:
dfd.resolve('success');
setTimeout(function() {
dfd.reject('sorry');
}, time);
return dfd.promise();
}
现在我们可以执行一些名为myFunc
的异步函数并处理超时:
// Attach a done and fail handler for the asyncEvent
$.when( timeout(myFunc, [some_args], 1000) ).then(
function(status) {
alert( status + ', things are going well' );
},
function(status) {
alert( status + ', you fail this time' );
}
);
好了,让我们在这个故事中来个转折吧!假设myFunc
本身返回一个promise (注意: promise没有延迟,我不能更改它):
function myFunc(){
var dfd = new jQuery.Deffered();
superImportantLibrary.doSomething(function(data)){
if(data.length < 5){
dfd.reject('too few data');
}
else{
dfd.resolve('success!');
}
}, {'error_callback': function(){
dfd.reject("there was something wrong but it wasn't timeout");}
}});
return dfd.promise();
}
现在,如果我将myFunc
包装在timeout
中,我将失去处理不同于超时的错误的能力。如果myFunc
发出进度事件,我也会丢失它。
所以问题是:如何修改timeout
函数,以便它可以接受返回承诺的函数,而不会丢失它们的错误/进度信息?
https://stackoverflow.com/questions/24183480
复制相似问题