asicfr
asicfr

Reputation: 1061

How to wrap a promise

How can i wrap a promise in another promise to track its start and end ? I tried several solutions, but my console.log are never executed :

var realPromise = myService.doItAsync();

var defer = $q.defer();
realPromise.then(function(result) {
    console.log("end at " + new Date().getTime()); // <====== never executed
    defer.resolve(result);
}, function(reason){
    console.log("end at " + new Date().getTime()); // <====== never executed
    defer.reject(reason);
});
return defer.promise;

See that jsfiddle for complete example : jsfiddle

Upvotes: 0

Views: 841

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37530

Looks like in your Fiddle you need to call $timeout.flush() so the promise resolves...

scope.useService();
timeout.flush();  // get timeout from the injector in beforeEach()
rootScope.$digest();

You can also simplify the code a lot by chaining and reusing the existing promises. For example, the example above can become...

console.log("begin at " + new Date().getTime());
var realPromise = fn.apply(this, arguments);
realPromise.finally(function(result) {
    console.log("end at " + new Date().getTime());
});
return realPromise;

Updated Fiddle

Upvotes: 2

Related Questions