这里是这样的服务的工作示例:
http://plnkr.co/edit/fJwRER?p=preview。
它创建一个$ q延迟的对象,当去抖动函数最终被调用时,它将被解析。
它创建一个$ q延迟的对象,当去抖动函数最终被调用时,它将被解析。
// Create an AngularJS service called debounce app.factory('debounce',['$timeout','$q',function($timeout,$q) { // The service is actually this function,which we call with the func // that should be debounced and how long to wait in between calls return function debounce(func,wait,immediate) { var timeout; // Create a deferred object that will be resolved when we need to // actually call the func var deferred = $q.defer(); return function() { var context = this,args = arguments; var later = function() { timeout = null; if(!immediate) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } }; var callNow = immediate && !timeout; if ( timeout ) { $timeout.cancel(timeout); } timeout = $timeout(later,wait); if (callNow) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } return deferred.promise; }; }; }]);
通过使用promise上的then方法,可以获得去抖动函数的返回值。
$scope.logReturn = function(msg) { var returned = debounce($scope.addMsg,2000,false); console.log('Log: ',returned); returned.then(function(value) { console.log('Resolved:',value); }); };
如果你连续多次调用logReturn,你会看到承诺记录过来,但只有一个解析的消息。