我总是遇到$ q的问题
这是一个示例,其中立即.then
触发了
function doit() {
var deferred = $q.defer();
var modalInstance = $modal.open({
template: '<p>this is modal</p><a ng-click="ok()">ok</a>',
controller: function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
}
});
modalInstance.result.then(function () {
console.log('ok');
deferred.resolve();
}, function () {
console.log('Modal dismissed');
});
return deferred.promise;
}
别处:
$scope.service.doit().then(
$scope.variable = 5
);
http://jsfiddle.net/IngoVals/stqwanhm/
在尝试为另一个.then根本不触发的类似设置建模时,我在Fiddle中得到了这个。这里发生了什么?
您正在将值传递5
到then
这里:
$scope.service.doit().then(
$scope.variable = 5
);
该代码如下运行:
$scope.variable
被赋值 5
赋值表达式的结果(即赋值5
)传递到then
无论这些事情发生的时候了,当你打电话then
。他们不等待承诺被兑现。
你想一个传递函数为then
,而是和具备的功能设置变量:
$scope.service.doit().then(function() {
$scope.variable = 5
});
现在,您要传递一个函数。代码中的功能不运行,直到它叫,它会在以后的承诺得到解决。
好消息和坏消息是,从ES6开始,这将变得更加简洁,因为ES6引入了“胖箭头”功能:
$scope.service.doit().then(() => $scope.variable = 5);
这还将创建一个函数并将其传递到then
(在启用ES6的引擎上)。
我说这既是好消息又是坏消息,因为它既简洁又好(好!),而且在阅读时也很容易错过(坏!)。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句