你可以解析angularjs承诺返回前? [英] Can you resolve an angularjs promise before you return it?

查看:192
本文介绍了你可以解析angularjs承诺返回前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个返回承诺的功能。但有些时候,请求的信息立即可用。我想将它包装在一个承诺使消费者并不需要做出决定。

I am trying to write a function that returns a promise. But there are times when the information requested is available immediately. I want to wrap it in a promise so that the consumer doesn't need to make a decision.

function getSomething(id) {
    if (Cache[id]) {
        var deferred = $q.defer();
        deferred.resolve(Cache[id]); // <-- Can I do this?
        return deferred.promise;
    } else {
        return $http.get('/someUrl', {id:id});
    }
}

和使用这样的:

somethingService.getSomething(5).then(function(thing) {
    alert(thing);
});

的问题是,回调不执行为$ P $对解决的承诺。这是做合法的事情吗?有没有更好的方式来处理这种情况?

The problem is that the callback does not execute for the pre-resolved promise. Is this a legitimate thing to do? Is there a better way to handle this situation?

推荐答案

简短的回答:是的,你可以解析AngularJS答应你回到它之前,它会表现为你所期望的。

Short answer: Yes, you can resolve an AngularJS promise before you return it, and it will behave as you'd expect.

JB Nizet的Plunkr但重构到了最初要求的范围内正常工作(即一个函数调用服务),实际上在现场。

From JB Nizet's Plunkr but refactored to work within the context of what was originally asked (i.e. a function call to service) and actually on site.

里面的服务...

function getSomething(id) {
    // There will always be a promise so always declare it.
    var deferred = $q.defer();
    if (Cache[id]) {
        // Resolve the deferred $q object before returning the promise
        deferred.resolve(Cache[id]); 
        return deferred.promise;
    } 
    // else- not in cache 
    $http.get('/someUrl', {id:id}).success(function(data){
        // Store your data or what ever.... 
        // Then resolve
        deferred.resolve(data);               
    }).error(function(data, status, headers, config) {
        deferred.reject("Error: request returned status " + status); 
    });
    return deferred.promise;

}

在控制器....

somethingService.getSomething(5).then(    
    function(thing) {     // On success
        alert(thing);
    },
    function(message) {   // On failure
        alert(message);
    }
);

我希望它可以帮助别人。我没有找到其他的答案很清楚。

I hope it helps someone. I didn't find the other answers very clear.

这篇关于你可以解析angularjs承诺返回前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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