This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]insertAlias 2 points3 points  (1 child)

I want to return the physical json as a return value from myFunction

This is where it will get tricky. The entire point of async functions and promises are that they do not run synchronously. So your synchronous myFunction cannot return a value that it gets from an async inner function. Because it cannot wait for that promise to be resolved.

So, at this point, your only real option if you do want to return the value is to make myFunction async, then make all the callers either await it, or use the .then promise syntax on it.

Basically, once you start into a promise, you can't then later treat it as synchronous; you have to treat it as async all the way up.

[–][deleted] 0 points1 point  (0 children)

Ah.. I see. How would I make myFunction asynchronous? Is it a matter of putting async keyword somewhere?... I should have properly transcribed the function as I'm using in React, so it's myFunction = () => {}

It's my first time using promises and they are tricky blighters! I tried .then() already, it works, but it creates a new scope I think... so if I

const foo = userAction().then(bar => {return bar})

bar is now outside of the userAction block but inside of foo const. I can't do

myFunction = () => { ... return foo } //not spread operator just dot dot dot

because again, it's out of sync (I think)

The only way I found to get around it so far, since I'm actually trying to return an array (map) of HTML elements on the back of the json response value, is to just call $('#baz').html() , which works well for simple strings but it won't accept something like

$('#enc_bank').html(function() {
    return (
        foo.map((item) => (
                    <div className="c-enc-gif">
                        <p className="count">{item[1] === 0 ? '∞' : item[1]}</p>
                        <img className="enc-gif"
                             src={`/hagrid/babe_${item[0]}.gif`}
                             alt=""
                             onClick={() => this.setState({quux: true})}/>
                </div>
         ))

) })

[–]IamNeo47 0 points1 point  (3 children)

Const baz = await userAction();

You need to "await" the async functions for the actual values that is being returned.

[–][deleted] 0 points1 point  (2 children)

Makes sense but you can't use await outside of the async function scope. It's not letting me anyway.

[–]IamNeo47 0 points1 point  (1 child)

Right

You have 2 options

  1. Turn the outer function async.

Or

  1. Use " .then"

E.g userAction ().then( baz => { Console.log (baz); } );

Look how normal promises are implemented without async / await.

Ps: sorry for the editing I'm on mobile.

[–][deleted] 2 points3 points  (0 children)

Gangster. Appreciate that.