我可以在AngularJS中使用$ q.all并使用不返回.promise的函数吗? [英] Can I use $q.all in AngularJS with a function that does not return a .promise?
问题描述
如果我有以下功能:
doTask1: function ($scope) {
var defer = $q.defer();
$http.get('/abc')
.success(function (data) {
defer.resolve();
})
.error(function () {
defer.reject();
});
return defer.promise;
},
doTask2: function ($scope) {
var defer = $q.defer();
var x = 99;
return defer.promise;
},
我被告知我可以等待这两个承诺:
I'm told that I can wait for both promises like this:
$q.all([
doTask1($scope),
doTask2($scope)
])
.then(function (results) {
});
如果任务2没有返回承诺怎么样?我在AngularJS的$ q文档
中看到有一个when。但是我不知道如何使用它
而且没有例子。
How about if task 2 does not return a promise? I saw in the $q documentation for AngularJS that there is a "when". However I am not clear on how to use it and there's no example.
是否必须让doTask2通过两行来返回一个承诺:
Is it the case that I MUST have doTask2 return a promise by having the two lines:
var defer = q.defer()
return defer.promise
或者有更简单的方法吗?ll
or is there an easier way to do this?ll
推荐答案
$ q.when用于你不喜欢的场景事先知道函数是返回promise还是直接值。
以下示例/ plunker显示了一个方法,其结果用于$ q.all,并且每次调用时返回不同类型的对象(int或promise):
$q.when is used in scenarios where you don't know upfront whether the function is returning a promise or a direct value.
The following example/plunker shows a method, whose result is used in $q.all, and which returns different type of object (int or promise) every time it's called:
app.controller('MainController', function($scope, $q, $http) {
var count = 0;
function doTask1() {
var defer = $q.defer();
$http.get('abc.json')
.success(function (data) {
defer.resolve(data);
})
.error(function () {
defer.reject();
});
return defer.promise;
}
/**
* This method will return different type of object
* every time it's called. Just an example of an unknown method result.
**/
function doTask2() {
count++;
var x = 99;
if(count % 2){
console.log('Returning', x);
return x;
} else {
var defer = $q.defer();
defer.resolve(x);
console.log('Returning', defer.promise);
return defer.promise;
}
}
$scope.fetchData = function(){
// At this point we don't know if doTask2 is returning 99 or promise.
// Hence we wrap it in $q.when because $q.all expects
// all array members to be promises
$q.all([
$q.when(doTask1()),
$q.when(doTask2())
])
.then(function(results){
$scope.results = results;
});
};
});
<body ng-app="myApp" ng-controller='MainController'>
<button ng-click="fetchData()">Run</button>
<pre>{{results|json}}</pre>
</body>
这篇关于我可以在AngularJS中使用$ q.all并使用不返回.promise的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!