0

Here is my initial attempt:

const fetch = require('node-fetch');
...
const getUserData = async function() {
    return await fetch('http://jsonplaceholder.typicode.com/users');
}

const usersStore = getUserData();
console.log(usersStore)

I get the result: Promise { <pending> }

Confused that I still got a Promise pending, I tried this:

const usersStore = getUserData()
.then(res => res.json())
.then(json => json);

but got the same result, so I tried this:

const getUserData = function() {
    const url = 'http://jsonplaceholder.typicode.com/users';
    return new Promise((resolve, reject) => {
        const result = fetch(url)
            .then(response => response.json)
            .then((json) => json);
        return resolve(result);
    });
}

Still same result.

The only thing that worked was an IIFE, but I didn't want to use that just to get my data.

Joey Garcia
  • 315
  • 3
  • 7
  • `const usersStore = getUserData(); console.log(usersStore)` You cannot retrieve a value which is retrieved asynchronously, synchronosly. You must wait for the Promise to resolve. – CertainPerformance Sep 05 '20 at 17:03
  • First of all, `await` in `return await ...` is unnecessary. As far as the question is concerned, you can access the data from the API inside a callback function of `then()` or inside an `async` function after awaiting the call to `getUserData()` – Yousaf Sep 05 '20 at 17:10
  • Thanks for you reply, but I think I was right on the initial attempt, I did everything right but I didn't realize that I needed to continue to use multiple thens to get the data. For example, getUserData().then(response => response.json()).then(data => console.log(data)) – Joey Garcia Sep 15 '20 at 18:58
  • Better yet, this would have worked too: ``` const usersStore = getUserData() .then(res => res.json()) .then(data => console.log(data)); ``` – Joey Garcia Sep 15 '20 at 19:04

0 Answers0