是否有一种简单的方法可以将成功调用返回到 $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?

查看:17
本文介绍了是否有一种简单的方法可以将成功调用返回到 $q.all 而无需创建 $q.defer() 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有许多同步和异步(执行 $http 调用)方法.在控制器我有这样的代码:

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 变量然后返回 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).

如何在不使用繁琐的延迟的情况下从一个值做出承诺?

How can I make a promise from a value without using tedious deferreds?

您可以使用$q.when:

return $q.when({
    data1: 99,
    data2: 123
});

如果该值还不是一个promise,则将返回一个promise,并尽快使用该值解析.请注意,这必然会在您的代码中引入异步,因此它不再是真正的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆