【发布时间】:2017-09-17 23:48:21
【问题描述】:
我已经阅读了很多关于这个问题的答案,但我就是不明白。承诺去哪儿了?我通过对云数据库的异步调用创建了一个简单的工厂:
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。稍后异步数据记录但不返回到控制器。我每天都在使用 Promise,但我无法弄清楚 Promise 的去向。
第二个问题:我需要toController: toController这行吗?我可以摆脱它吗?
谢谢!
【问题讨论】:
-
承诺不会去任何地方,因为不是返回它,而是返回 47。阅读blog.ninja-squad.com/2015/05/28/angularjs-promises。关于“我是否需要 toController: toController 这一行”,嗯,不,但是你的服务根本没有方法,而且真的没用。
标签: angularjs firebase asynchronous angular-promise