0

how to get the resolved value directly in angular promise?
I want to get the string "ok" in below function, not the promise object.
anybody help??

var getReturn = function() {
        var defer = $q.defer();
        var promise = defer.promise;
        defer.resolve("ok");
        return promise.then(function (value) {
            console.log(value);
            return(value);
        });
    };
1
  • could your clarify your question a bit more? it is not quite clear what you want to achieve. where do you want to get what value and why? Commented Mar 17, 2016 at 8:09

2 Answers 2

2

Since the function is not asynchronous, there's no need for a promise. So the correct way doing so will be:

var getReturn = function() {
  return "ok";
}

If you still want this as a promise you should do as follows:

var getReturn = function() {
        var defer = $q.defer();
        setTimeout(function() {
           defer.resolve("ok");
        },0)
        return defer.promise;
    };

And wherever you call the function do the then:

getReturn().then(function (value) {
            console.log(value);
        });
Sign up to request clarification or add additional context in comments.

2 Comments

the actual scenario is that I want to send a request to load some data, and after got the data to do something: someService.getData().then(function (data) {xxxxx});
just replace the setTimeout fn I wrote with your http request, and when you get the response you can resolve or reject with the response
0

You can't actually do that when you are dealing with promises. Promises are meant to be awaited or deferred until the expected value is ready meaning you should get the value only in it's "then" block especially if it's an $http promise.

2 Comments

I just want to do something after the http request done, but I'm confused where to write the code.
You either right it in your controller or service associated with the $http request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.