-2
    return fetch(url)
    .then(response => response.json())
    .then(json => {
        //everything just here?
    })
    .catch(err => console.log(err));

Hello guys i have a newbie question. If i want to get some data from server and manage them (create new html elements, draw some canvas) am i forced to do it this way in ".then" chain? Im asking because its quite unintuitive. And ill be glad for some example of code like this, just get data from server and create/edit some html elements. Thanks!

C233
  • 35
  • 3
  • 3
    Look into async await it's more intuitive – Keith Jan 18 '21 at 01:21
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Jan 18 '21 at 01:46
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Zac Anger Jan 18 '21 at 01:47

2 Answers2

3

You can do it in more intuitive way like this

getDataFromServer(url) {
    return fetch(url)
    .then(response => response.json());
}

async yourMainFunction() {
    const data = await getDataFromServer(url);
    ////everything just here with data from server? 
}

one thing to note that for using await you have to make your function marked with async

mss
  • 1,423
  • 2
  • 9
  • 18
2

You are correct, the only place the response json is avalable is in the second then() callback.

You could create a function that contains your html/canvas logic and then call that function in the response callback.

fetch(url)
.then(response => response.json())
.then(json => {
  handleResponse(json) // ⭐️
})
.catch(err => console.log(err));

function handleResponse (json) {
  // ⭐️ everything in here
}
cam
  • 3,179
  • 1
  • 12
  • 15