延迟对象在被调用时被.reject()
拒绝.rejectWith()
。
这是一个例子:
var deferred = $.Deferred();
deferred
.done(function() { console.log('done') })
.fail(function() { console.log('failed') });
deferred.resolve(); // <-- will write 'done' to console
deferred.reject(); // <-- will write 'failed' to console
您可以使用 deferreds 使异步函数的行为与$.get()
实际相同。例如setTimeout
:
function MyTimeout() {
var deferred = $.Deferred();
setTimeout(function() {
// as a demo, this will reject the deferred half the time
if (Math.random() < 0.5)
deferred.reject();
else
deferred.resolve();
}, 2000);
return deferred.promise();
}
MyTimeout()
.done(function() { console.log('done') })
.fail(function() { console.log('failed') });
最后一条语句也可以写成:
MyTimeout().then(
function() { console.log('done') },
function() { console.log('failed') }
);