我读过这个问题的很多答案,但我只是不明白。承诺去了哪里?我做了一个简单的工厂,一个异步调用云数据库:AngularJs返回异步工厂?
app.factory('asyncFactory', function() {
let toController = function() {
firebase.database().ref('en').once('value') // get the array from the cloud database
.then(function(snapshot) { // take a snapshot
console.log(snapshot.val()); // read the values from the snapshot
return snapshot.val(); // this returns later
});
return 47 // this returns immeadiately
};
return {
toController: toController // why is this necessary?
}
});
我把它从我的控制器:
$scope.words = asyncFactory.toController();
console.log($scope.words);
这里的响应:
正如你可以看到,47
立即返回给控制器。如果我注释掉return 47
,那么工厂返回undefined
。稍后,异步数据日志但不会返回到控制器。我每天都在使用承诺,但我无法弄清楚承诺的去向。
第二个问题:我需要行toController: toController
?我可以摆脱它吗?
谢谢!
承诺并没有去任何地方,因为它不是返回它,而是返回47.阅读http://blog.ninja-squad.com/2015/05/28/angularjs-promises/。关于“我是否需要线路toController:toController”,好吧,不,但是那么你的服务根本就没有办法,而且真的没用。 –