zabop
zabop

Reputation: 7852

How to check what an async function returns

I am aware of the questions JavaScript wait for asynchronous function in if statement [duplicate] and How do I return the response from an asynchronous call?, but (maybe because I am an absolute JS beginner) I am not able to implement those ideas.

Using async await documentation, I can make this example work:

let hello = async () => { return "Hello" };
hello().then((value) => console.log(value))

It just outputs Hello. However, I would like my code to check what the function hello returns at some later point. Something like this:

if ( /* what comes here? */) {
    console.log("Hello was said")
}

How could I do this? How to formulate this if statement to check if hello indeed returned "Hello"?

Upvotes: 0

Views: 1576

Answers (4)

Sô Đa Chanh
Sô Đa Chanh

Reputation: 11

  1. async/Promise introduces an independent execution that would block otherwise
  2. "Later" happens at the completion of its blocking thread
  3. The callback you attach to .then() gets executed at that "later" time

Here is an example that may clear up some of the fog.

  • Note the two independent threads after setFree() is called.
  • gone() has gone on to do its own thing
  • setFree() returns immediately.
  • A common variable waitOver is shared between the two executions
  • The then() handler "knows" and takes care of things at that "later" time
  • That handler updates the common variable waitOver to inform those interested in knowing what happens at that "later" time

"

let waitOver = false;

let whatToDo = setFree("Jill",5);
console.log(whatToDo);

let theWait = setInterval( () => {
  
    waitOver ? clearInterval(theWait) :
    console.log(" and .. wait");
}, 1000);



function gone(secs) {
    return new Promise(resolve => setTimeout(resolve, secs*1000));
}

function setFree(someone,secs) {
    
    console.log(`If you truly love ${someone}, set ${someone} free`);

    gone(secs).then(() => {
        console.log(`Back! ${someone} is yours`);
        waitOver = true;
        return  `${someone} is yours`;
      }).catch(`Hunting ${someone} down and kill ${someone}`);   
    return " Here you wait ... ";
}

This is what you'll get:

    If you truly love Jill, set Jill free
     Here I wait ... 
     and .. wait
     and .. wait
     and .. wait
     and .. wait
    Back! Jill is yours*

NOTICE ALSO that after calling setFree(), any check on waitOver in the main execution thread would be false unless that check is made after gone() has been handled by its .then() handler.

If there is no .then() handler then gone() would have gone to the woods, and you will never know if Jill ever came back, even if she did because that completion was never handled :-)

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12036

hello().then((value) => ...) basically means that if the promise (await) is fulfilled, it should call a function(value = <return_value>){} ... so...

hello().then((value) => {
    if(value == 'Hello'){
        console.log("Hello was said");
    }
});

Upvotes: 1

Pascal K
Pascal K

Reputation: 128

The if statement can be wrapped in an async function like this:

let hello = async () => { return "Hello" };

async function foobar() {
  if(await hello() == 'Hello')
    console.log('yay')
}

foobar()

await can only be used in async functions.

Promises continue giving you promises as a return, but await can evaluate a Promise in an async function.

Upvotes: 0

Ethanolle
Ethanolle

Reputation: 1223

It depend on what you mean for "Later".

  1. you can save it as a regular variable and export it(it is not a matter of async-await) Export Variables.
  2. and if you want to do it in a safe way and "later" is someday after you need to send it to a DB.

Upvotes: 0

Related Questions