Search code examples
javascripthtmlajaxfetch

fetch pure javascript handling promises


    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!


Solution

  • 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
    }