0

I have a function which needs to be async (because of await sleep()) and I want it to return a String not a Promise by calling it from another non-async function.

async function _getString() {
    await sleep(50);
    return "Hello World";
}
// BY DOING THAT:
function getString() {
    return _getString().GET_PROMISE_VALUE();
}

I know currently of two possibility to get the value of the Promise:

  1. await getString()
  2. getString().then((result) => {anotherVariable = result});

The problem is:

  • I want to pause code execution where the function is called, because then anotherVariable might get used before it gets assigned to result
  • I don't want to use await because I would need another async function

Is there a way to make getString() wait until _getString() finished and then get the result?

  • 1
    Nope, using `.then` or `await` are the only real possibilities. – CertainPerformance Nov 15 '20 at 03:09
  • 2
    The only way to get an asynchronous result synchronously is with a time machine or a psychic - neither of which are present in javascript – Jaromanda X Nov 15 '20 at 03:22
  • Ok, i will see what i can do then. Thanks for your answers though! :) – thatDude767 Nov 15 '20 at 12:26
  • 1
    Just in case it was not crystal clear -- functions defined with the `async` keyword *always*, *without exceptions* return `Promise` objects, in practice -- even with `return something` statements for any type and value of `something`. Your values are thus always "promisified" -- turned into a promise that resolves with the value you specify in a `return` statement. That's it, basically. – Armen Michaeli Nov 15 '20 at 12:35

0 Answers0