Craig Craig - 2 years ago 104
AngularJS Question

How to return data from promise

I need to get the out of the promise so it can be returned by the enclosing function. I know I probably can't do it the way I've coded it because of normal javascript scope. Is there any way it can be done?

The console.log at #1 produces the correct data. console.log #2 always produces 'a';

function addSiteParentId(nodeId) {
var theParentId = 'a';
var parentId = relationsManagerResource.GetParentId(nodeId)
theParentId =;
console.log(theParentId); // #1
console.log(theParentId); // #2
return theParentId;

Any pointers would be appreciated.

Answer Source

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download