Search code examples
javascriptnode.jspromisefetch

How to resolve multiple then() promise into one


In this code I used multiple then() methods, I just want to convert it into only one then, How it is possible.

getGreeting = () => {
  fetch(url)
    .then((response) => response.json())
    .then((result) => result.data)
    .then((data) => printCards(data))
    .catch((err) => {
      console.log(err);
    });
};

Solution

  • notice the async and await keywords

    fetch(url)
        .then(async (response) => {
          const json = await response.json();
          printCards(json.data);
         })
        .catch((err) => {
          console.log(err);
        });
    };