0

I want to call an async function (some REST call), that returns a promise. I need the result of the promise to continue, until then my code should wait.

Now I know this is not state-of-the-art anymore, but I have to use ES 5, so no async await.

Maybe I'm going about this all wrong so far, but my current state looks something like this:

var someAsyncCall = function() {
  var deferred = $.Deferred();
  deferred.resolve.apply(deferred, ['2']);
  return deferred.promise();
};

// Call the async service
var getValue = function () {
  var result = null;
  someAsyncCall().then(function (value) {
    result = value;
  });
  return result;
};


// Synchrounus code which needs to be executed in this order.
console.log('1');

var result = getValue();
console.log(result);

console.log('3');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Lohmi
  • 73
  • 5
  • 1
    `result = value` won't do what you think. – evolutionxbox Sep 26 '22 at 09:31
  • 2
    You need to put the `return result` inside the `then`, otherwise it gets executed before the async is done. – Geshode Sep 26 '22 at 09:33
  • 1
    @Geshode and then it means that `getValue` returns `undefined`. since there is no `return` statement in it. Coupled with the fact that [`.then(function(a){ return a; })` is a no-op](https://stackoverflow.com/questions/41089122/is-thenfunctiona-return-a-a-no-op-for-promises) the real code is just `return someAsyncCall()` which then simplifies to `getValue = someAsyncCall` – VLAZ Sep 26 '22 at 09:42
  • I thought something like this is the case. But even if I do return the value directly I still have the problem of receiving a promise that could be resolved at any point in time. – Lohmi Sep 26 '22 at 10:18
  • @Lohmi you cannot transform async code to synchronous. Even with `async`/`await`. See [async/await implicitly returns promise?](https://stackoverflow.com/q/35302431). A promise *always* settles "later" than the current synchronous code. `await` (which only works in async functions) makes the current context *seem* like it's executed synchronously but it does not block execution. Even with an `await` a function will always produce a promise. Since there is no way to change such a result, the other option is to use the Promise API and use a `.then()` on the promise to handle it. – VLAZ Sep 26 '22 at 10:24

0 Answers0