有没有一种简单的方法来返回成功调用$ q.all而无需创建一个$ q.defer()的变量? [英] Is there an easy way to return a success call to $q.all without having to create a $q.defer() variable?
问题描述
我的应用程序有许多同步和异步(做$ HTTP调用)方法。在
控制器我有code是这样的:
My application has a number of synchronous and asynchronous (doing a $http call) methods. In the controllers I have code like this:
$q.all([
asyncMethod1(),
syncMethod1()
])
.then(function (results) {
虽然我没有必要等待在syncMethod1()我把这个$ q.all内让事情变得简单,让我
更改为异步如果我将来想要的方式。
Even though I have no need to wait on the syncMethod1() I put this inside the $q.all to keep things simple and to allow me to change the method to async if I wanted in the future.
有关的同步功能,我称他们是这样的:
For the sync functions I am calling them like this:
var syncMethod1 = function () {
var defer = $q.defer();
var abc = 99;
defer.resolve({
data1: abc,
data2: 123
});
return defer.promise;
};
我想知道什么是,如果有,我可以有同步的方法返回$ q.all数据,但如果没有了我
需要创建一个延迟变量,然后做defer.promise的回报?只是试图让同步方法那样简单
越好。
What I would like to know is if there's a way that I can have the sync method return to the $q.all the data but without my needing to create a defer variable and then do a return of the defer.promise? Just trying to make the sync method as simple as possible.
推荐答案
$ q.all
可以,即使没有记录,采取纯值,以及不仅承诺(它会自动将其转换)。您的同步方法应该只是做
$q.all
can, even if not documented, take plain values as well and not only promises (it will automatically convert them). Your sync method should just do
return {
data1: 99,
data2: 123
};
这是最简单的事(可以在真正的同步环境中使用也一样)。
which is the most simplest thing (and can be used in really synchronous contexts as well).
我怎样才能从一个值承诺不使用繁琐的deferreds?
How can I make a promise from a value without using tedious deferreds?
您可以使用 $ q.when
:
You can use $q.when
:
return $q.when({
data1: 99,
data2: 123
});
如果值是不是已经承诺,则承诺将返回一个与价值尽快解决。请注意,这必然在code介绍异步,所以它不是一个真正的 syncMethod
了。
If the value is not already a promise, then a promise will be returned that is resolved with the value as soon as possible. Notice that this will necessarily introduce asynchrony in your code, so it's not really a syncMethod
any more.
这篇关于有没有一种简单的方法来返回成功调用$ q.all而无需创建一个$ q.defer()的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!