0

I have a chain promises and I want to return an object instead of a promise. Instead I get a promise. This is the function:

self.get = function(id) {
    var parameters = [id];
    var orders     = {}
    return DBA.queryAgent("SELECT * FROM Orders WHERE " + column_id + " = ?", parameters).then(function(result) {
        return DBA.getById(result);
    }).then(function(result) {
        order = result;
        return self.getProdutcs(id);
    }).then(function(result) {
        order.Products = result;
        return order;
    });
}

I expect that

service.get(1)

returns an object, I get a promise. Where am I wrong?

Thank you

2 Answers 2

2

From the angular docs https://docs.angularjs.org/api/ng/service/$q

calling the then method of a promise returns a new derived promise,

It is the way angular is written. Hence, you have to access it like this.

 service.get.then(function(result) {
    // whatever
  });
Sign up to request clarification or add additional context in comments.

1 Comment

I got it, thanks. I had forgotten the asyncronous fact.
1

You can access the value by doing the following:

  service.get.then(function(result) {
    console.log(result);   
  });

7 Comments

I know I can do that, but I want understand how I can NOT do that.
The then() function returns a promise. It's how they work. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
If you don't want it to return a promise then you can run run the command synchronously and block the thread or pass a callback function to the get method and invoke that instead of using an anonymous function. The point of promises is to do neither of those things
Thanks to both, you are right. I was forgetting the asynchronous fact
Not sure why my answer didn't get marked as the selected answer or get an upvote :( It contained all the necessary information.
|

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.