0

I'm new to this whole concept of asyncronous programming in JS, and I'm a little bit unsure why this is happening. This is my code

const fetch = require('node-fetch');
const apiSite = `https://api.github.com/users/`;

const getGithubUserObject = async (username) => {
    let settings = {method: "GET"};
    try {
        const response = await fetch(apiSite + username, settings);
        const responseJson = await response.json();
        return await responseJson;
    }
    catch(e) {
        console.log(`Error + ${e}`);
    }
}

let myObj = getGithubUserObject("example");
console.log(myObj);

The problem I encountered is that myObj is a Promise, but in getGithubUserObject I'm returning await responseJson, and it's waiting for response to be done. If instead of returning it I print it out it works fine. Is this an intended behaviour of async/await? How can I return the value without using .then() or similars outside the function?

Norhther
  • 545
  • 3
  • 15
  • 35
  • 1
    Async functions always return Promises. To get to the resolved value, you must wait for the Promise to resolve with `.then`, or `await` it, there's no other good solution – CertainPerformance Dec 30 '19 at 23:51
  • @CertainPerformance but I'm using await in responseJson. So you mean that event using await there, responseJson is going to be a Promise? – Norhther Dec 30 '19 at 23:54
  • `responseJson` won't be a `Promise`, you can return it without that extra `await` (you did the wait in the previous line). But, your entire function is `async` (and there is no `await` without that), and that is why whatever it returns is going to be wrapped into a `Promise`. – tevemadar Dec 31 '19 at 00:05
  • So basically I will have to stick with `then` or create an anonymous async function at top level, right? So there's no way to store the result of the promise in a variable in a elegant/useful way? – Norhther Dec 31 '19 at 00:08
  • That's right, you can't simply store the result of an async call in a top level variable like that because it'd block the script and become synchronous. But the "elegant/useful" remark isn't exactly inaccurate because asynchronous code isn't supposed to behave like synchronous code by design, so it's a matter of shifting your approach/perspective (any functions that depend on this promised result can `await` it, for example). – ggorlen Dec 31 '19 at 04:49

0 Answers0