0

I am attempting to get an object from a REST API using a javascript Promise. The issue I am running into is the promise will not resolve unless I am debugging and use a breakpoint. I know there are several questions posted regarding this issue but none seem to provide an answer, so I am trying again. Here is my code (NOTE: placing a breakpoint at "return values" causes the promise to populate the values object EVERY TIME. Without the breakpoint the object NEVER gets populated.)

function GetSession(userClient, userId) {

  var user = { userId: '', name: ''};
  
  userClient.session.get(userId)
    .then(function(result) {
      user.userId = result.userId;
      user.name = result.name;
    })
    .catch(err => alert(err));
  
  return user;
}

Anyone have any ideas why this fails when not debugging?

Hoodlum
  • 1,443
  • 1
  • 13
  • 24
  • 2
    The promise still resolves even without the breakpoint. It's just that it resolves *after* the return, because that's how asynchronous code works. When you add the breakpoint it lets the promise finish before the rest of the code runs. But obviously you can't do that in production code, so you'll need to learn how to handle async calls properly instead. – John Montgomery Nov 22 '21 at 19:16
  • @JohnMontgomery - Everything I can find tells me the Promise handles that under the hood, which is one of the primary reason for using it instead of an AJAX call. – Hoodlum Nov 22 '21 at 19:28
  • Promises simplify things a lot, but they're still asynchronous. There's no getting around that, even async/await just pushes the responsibility for dealing with it further up the chain. – John Montgomery Nov 22 '21 at 19:46
  • So I still can't find an answer to my question. Anywhere. What am I doing wrong? – Hoodlum Nov 22 '21 at 19:55
  • @Hoodlum Have you read the question and answered linked in the blue box above your question? That should answer your question. – Ivar Nov 22 '21 at 20:00
  • Yes, I have. The answers provided don't differ that much from everything else I have found. Based on that and others it seems like my code should be working. – Hoodlum Nov 22 '21 at 20:36
  • @Hoodlum Then you didn't fully understand it I'm afraid. Or did you read the question as if it were an answer? Because your code looks an awful lot like the last example in the question there, as an example of what _doesn't_ work. – Ivar Nov 22 '21 at 20:45
  • @Hoodlum The linked question gives several different ways to handle asynchronous code. They don't differ from everything else you've found because that's how you're supposed to do it. The only way to make it work similarly to how it does in your question would be to use async/await instead of `then`, but if you do that you'll have to handle it asynchronously in whatever code calls the function instead. – John Montgomery Nov 22 '21 at 21:19

0 Answers0