-1

I'm trying to learn how to replace callback functions with async and await. After two days I have the following working in that it will write the json to the console from inside the function.

const requestRoster = async ()=> {
    const response = await fetch('/testing/getRoster.php', {
        method: 'get',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    const json = await response.json()
    console.log(json); // writes the array json to the console
    return json; //apparently returns a pending promise
}



However, when I say

$roster = requestRoster();
console.log ($roster); // writes Promise{<pending}> to the console
​

The console reports

Promise {} When I expand this line, I see:

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(64)

and Array(64) contains the data I want.

Obviously I'm a bit lost here. Apparently the function requestRoster() is returning a pending promise. What I want is for it to return the Array(64). So, where am I going wrong? I simply want requestRoster() to return the Array(64)

Thanks,

Dave Davis
  • 574
  • 1
  • 4
  • 14

3 Answers3

3

When you use the async keyword the function automatically returns a Promise.

And the await keyword is used to wait for the promise to resolve.

You can easily do it like that:

$roster = await requestRoster();

But note that this can only be done in a function that is async itself. If you want to use it on top level you can use a IIFE (Immediately-Invoked Function Expression) like this:

(async () => {
  $roster = await requestRoster();
  // do something with $roster here
})();
Simon Zyx
  • 6,503
  • 1
  • 25
  • 37
1

An async declared function returns a promise, even if you return a simple value. If you return such a value it gets wrapped into a already resolved Promise which you can read out the known ways.

If you are in another async function, you can await it.

$roster = await requestRoster();

In a simple function or arrow function you can use the promise methods.

requestRooster().then( (roster) => { /* do something with rooster*/ } );
Peter Paul Kiefer
  • 2,114
  • 1
  • 11
  • 16
-5

just remove await from this line:

const json = await response.json()
Wepster
  • 11
  • 4