[英]Service return empty promise
I have service in which I simulate http request. 我有模拟http请求的服务。
eg I have array of object users: 例如,我有对象用户数组:
var users = [{
id: 1,
name: 'Name1',
groupId: 2
}, {
id: 2,
name: 'Name2',
groupId: 1
}];
And I have function which ask for it: 我有要求的功能:
this.getUser = function(userId) {
return this._returnLater(users.filter(function(user) {
return user.id === userId;
})[0]).then(angular.copy);
};
and use function returnLater
which basicly just set timeout randomly 并使用
returnLater
函数,该函数基本上只是随机设置超时
this._returnLater= function(response) {
return $timeout(function() {
return response;
}, Math.random() * 2000);
};
This looks well for me. 这对我来说很好。 However If I try to run this code from my directive as:
但是,如果我尝试从我的指令运行以下代码,则:
var promise = UserService.getUser(1);
promise.then(function(res) {
aeCtrl.user = res;
});
my aeCtrl.user
is empty, if I try to console.log(promise)
before promise.then
i get this: 如果我尝试在
console.log(promise)
之前尝试console.log(promise)
,则我的aeCtrl.user
为空promise.then
Is here someone who can advise me what I'm doing wrong? 这里有人可以告诉我我在做什么错吗?
You probably need to return a new promise and resolve it in the timeout 您可能需要返回新的诺言并在超时后解决它
this._returnLater= function(response) {
return new Promise(function(resolve) {
$timeout(function() {
resolve(response);
}, Math.random() * 2000);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.