作为扩展of a question I asked earlier(感谢所有帮助!),
我无法让我的第二个承诺工作(在一个3或更多的链中)
我查看了this,this,但无法获得我当前代码的任何线索
应用和控制器看起来像:
myApp.controller('Controller_1', function($scope, myService) {
var myName = "Ben";
myService.slowService(myName)
.then(function(result){myService.slowService2(result);})
.then(function(result){myService.fastService(result);});
$scope.myName = myName;
});
服务提供商看起来像:
myApp.service('myService', function($q, $timeout) {
this.slowService = function (name) {
var deferred = $q.defer();
console.log('Start of slowService1:', name, Date.now());
$timeout(function() {
name = 'Hello, ' + name + " is learning Angularjs";
alert(name);
deferred.resolve(name);
console.log('End of slowService1 timeout:', name, Date.now());
}, 1500);
return deferred.promise;
};
this.slowService2 = function (name) {
var deferred = $q.defer();
console.log('Start of slowService2:', name, Date.now());
$timeout(function() {
name = 'Hello, ' + name + " is learning Angularjs";
alert(name);
deferred.resolve(name);
console.log('End of slowService2 timeout:', name, Date.now());
}, 1000);
return deferred.promise;
};
this.fastService = function(name){
var deferred = $q.defer();
console.log('Start of fastService:', name, Date.now());
alert('Hello ' + name + ' - you are quick!');
deferred.resolve();
console.log('End of fastService:', name, Date.now());
return deferred.promise;
};
});
控制台输出如下:
Start of slowService1: Ben 1420877247858
End of slowService1 timeout: Hello, Ben is learning Angularjs 1420877250982
Start of slowService2: Hello, Ben is learning Angularjs 1420877250983
Start of fastService: undefined 1420877250984
End of fastService: undefined 1420877251641
End of slowService2 timeout: Hello, Hello, Ben is learning Angularjs is learning Angularjs 1420877254148
因此,当第一个slowService1
$ q.defer()工作时,第三个函数fastService
不会等待第二个slowService2
延迟对象在开始之前解析... ?
jsfiddle是here
PS $ timeout仅用于模拟$ http调用和SQLite查询等。
答案 0 :(得分:4)
您需要return
承诺,以便与.then
链接:
myService.slowService(myName)
.then(function(result){
return myService.slowService2(result);
})
.then(function(result){
myService.fastService(result);
});