gpt4 book ai didi

javascript - angularjs 延迟 promise 不延迟

转载 作者:行者123 更新时间:2023-12-04 01:40:12 25 4
gpt4 key购买 nike

努力让 promise 在 angularjs 服务提供者中正常工作我读过 docs以及许多示例( hereherehere ),我想我的语法没问题(尽管显然出了点问题)

应用模块和 Controller 看起来像

var myApp = angular.module('myApp', []);

myApp.controller('Controller_1', ['$scope', 'Service_1', function($scope, Service_1) {

var myName = "Ben";

Service_1.slowService(myName)
.then(Service_1.fastService(name));

$scope.myName = myName;
}]);

服务(具有慢速功能)如下所示:

myApp.service('Service_1', function($q) {
this.slowService = function (name) {
var deferred = $q.defer();
console.log('Start of slowService:', name, Date.now());

setTimeout(function() {
console.log('setTimeout name:', name, Date.now());

if(name){
name = 'Hello, ' + name + " is learning Angularjs";
alert(name);
console.log('name:', name);
deferred.resolve(name);
} else {
deferred.reject('No name supplied !');
}
}, 3000);

return deferred.promise;
};

this.fastService = function(name){
console.log('Start of fastFunction:', name, Date.now());
alert('Hello ' + name + ' - you are quick!');
};
});

控制台输出如下所示:

Start of slowService: Ben 1420832940118
Start of fastFunction: result 1420832940122
setTimeout name: Ben 1420832948422
name: Hello, Ben is learning Angularjs

fastServiceslowService 之前开始完成,尽管在 Service_1 中使用了延迟对象/ promise 和一个 .then在 Controller 中...

谁能指出代码有什么问题?

jsfiddle 是 here

编辑: 将快速功能放入服务中,这样就不会与提升等混淆 - 仍然是相同的结果 - js fiddle 已更新

最佳答案

The fastService is starting before the slowService completes

那是因为您在 slowService 异步回调运行之前执行 fastService 函数。相反,您需要提供该函数的引用。即 .then(Service_1.fastService(name)); 应该是 .then(Service_1.fastService);.then(function(name){ Service_1. fastService(name); }); 否则 fastservice 将在 slowService 的异步部分运行之前立即运行。

使用 $timeout 的好处是它已经返回了一个 promise ,所以你不需要创建一个延迟对象并导致 deferred anti-pattern .

myApp.service('Service_1', function($q, $timeout) { //<-- Inject timeout
this.slowService = function (name) {
console.log('Start of slowService:', name, Date.now());

return $timeout(function() {
console.log('setTimeout name:', name, Date.now());

if(name){
name = 'Hello, ' + name + " is learning Angularjs";
return name; //return data
}
//Reject the promise
return $q.reject('No name supplied !');

}, 3000);


};
//...
});

并且在消费时只是链式:

  Service_1.slowService(myName)
.then(Service_1.fastService);

因此,即使您在原始方法中使用 $http,也不会超时,只是从 http 返回 promise ,而不是创建延迟对象。另外请记住,当您使用语法 .then(Service_1.fastService); 并且如果您在快速服务中引用 this 上下文,它不会是服务实例.

关于javascript - angularjs 延迟 promise 不延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com