3

How can i access a returned value from then() in JavaScript?

I have the following function:

function getResult(){
  var promise = _myService.getAge();
  var getResultPromise = promise.then(function(age){
    return age;
  })
  return getResultPromise; //How do i get the age (value) here?  *see image*
}

Or how would i access the value in the $$state object below?

enter image description here

m0meni
  • 16,006
  • 16
  • 82
  • 141
1future
  • 255
  • 5
  • 21
  • 2
    You don't...you have to return the promise itself, and then access it using .then from where you call your function. It's impossible to get a value out of a promise unless you're using something like async/await which is just syntactic sugar over generators. – m0meni Apr 06 '17 at 15:23
  • You can try using promise.all() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – Raj Apr 06 '17 at 15:27
  • 3
    @Raj that doesn't make sense. He's not returning a collection of promises. – m0meni Apr 06 '17 at 15:29
  • you can't do that...you have to wait till promise resolves to return getResultPromise – kaushlendras Apr 06 '17 at 15:31
  • take a look at my snippet and let me know if it works for you – John Vandivier Apr 06 '17 at 16:06
  • @kaushlendras uhm. no, getResultPromise IS a promise, so he can return it immediately. he just can't get a value from it without using .then(). – Kevin B Apr 06 '17 at 16:30
  • My answer was updated to perhaps get closer to OP's intent. If my answer helped please upvote and if not please let me know how to fix it. – John Vandivier Apr 06 '17 at 16:51
  • Well, this title shows now a completely different meaning (maybe the correct one according to the OP intent) from the original one. – lealceldeiro Apr 06 '17 at 17:08
  • possible (exact) duplicate of http://stackoverflow.com/questions/37337517/how-to-read-data-out-of-angular-resource-promise – Kevin B Apr 06 '17 at 18:03

1 Answers1

-2

How about this:

//The simple solution, this is how to use a Promise:

let _myService = {
  getAge: function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(3)
      }, 500);
    })
  }
};

function getResult() {
  _myService.getAge().then(function(age) {
    console.log(age);
  });
}

getResult();

//OR, maybe closer to OP's intended implementation, put the value in an outer state:

let outerState = {
  age: 0
};

setTimeout(function() {
  console.log(outerState)
}, 450);

let _myService2 = {
  getAge: function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(8)
      }, 750);
    })
  }
};

function addAgeToOuterState() {
  pState = new Promise(function(resolve, reject) {
    _myService2.getAge().then(function(newAge) {
      outerState.age = newAge;
      resolve(outerState);
    });
  });

  pState.then(function() {
    console.log(outerState);
  });

  return pState;
}

addAgeToOuterState()

//for fun
.then(function(outer) {
  console.log(outer); //state is still here
});
John Vandivier
  • 2,158
  • 1
  • 17
  • 23
  • 1
    That's to simulate an async function to show how the promise works. It's obviously not a drop-in, and also hard coding age === 3 is obviously not a drop in. – John Vandivier Apr 06 '17 at 16:13
  • 2
    My bad I'm just mad for no reason...regardless this answer just logs to console and returns undefined – m0meni Apr 06 '17 at 16:13
  • It logs 3 to the console because you have it log to console inside of the `.then`, and it returns undefined because getResult doesn't return anything. What I fail to see is how this helps answer the question in any way. – m0meni Apr 06 '17 at 16:17
  • 2
    @AR7 ... he's demonstrating the correct way to get the value. obviously it's impossible to get said value outside of a callback. – Kevin B Apr 06 '17 at 16:25
  • @KevinB I just don't see where the value is. The OP seems to be wondering how to pull the value in the promise into his angularjs state, but this answer is basically just a hello world promise example. – m0meni Apr 06 '17 at 16:29
  • I think this answer is way over-complicating the problem, but it does include the one thing that the op is missing; using `.then` on `getResult`'s return. – Kevin B Apr 06 '17 at 16:32
  • OP doesn't use getResult().then(). Yes, it's a hello world promise. Because the whole issue is OP used a promise incorrectly. – John Vandivier Apr 06 '17 at 16:35
  • @KevinB I should probably just abandon this thread at this point...I think we're in agreement and if I were to disagree with you I'd be nitpicking. I'll remove my downvote. – m0meni Apr 06 '17 at 16:36
  • @AR7 thanks for removing the downvote but I added appending to an outer state object. If you think this is what OP wanted please upvote. – John Vandivier Apr 06 '17 at 16:50
  • Also, if anyone else knows why this answer has downvotes please let me know. I think I answered OP's question quite well. – John Vandivier Apr 06 '17 at 16:51