如何包装承诺

时间:2014-11-04 21:11:10

标签: angularjs promise wrapper

我如何将承诺包含在另一个承诺中以跟踪其开始和结束? 我尝试了几种解决方案,但我的console.log从未执行过:

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;

请参阅jsfiddle以获取完整示例:jsfiddle

1 个答案:

答案 0 :(得分:2)

在您的小提琴中,您需要致电$timeout.flush(),以便承诺解决......

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

您还可以通过链接和重用现有的承诺来大量简化代码。例如,上面的例子可以变成......

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