fetch API with promise(then catch) - 01

With fetch() API, we can retrieve data from the server. fetch() API takes a URL as a parameter and returns a promise.


Then we can get a response object as a resolved value by chaining with “then” from the promise. From the response object, we can transform or retrieve the actual data with the .json() method.


After the next chaining, we can work with actual data as with our demand.


function myPromise() {
  const promiseData = fetch('https://jsonplaceholder.typicode.com/todos');
  promiseData
    .then((resData) => resData.json())
    .then((data) => console.log(data)); 
    return promiseData;
  }
   
console.log(myPromise());


When we create a custom promise, then we have to return the promise like...

function myPromise(control) {
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          if (control) {
            resolve();
          } else {
            reject();
          }
        }, 3000);
      });
    }


This functionality has been done by an API like fetch(). We only have to call the returned promise like…

myPromise(true)
     .then(function () {
       console.log("Promise has been resolved");
     })
     .catch(function () {
       console.log("Promise failed");
     })
     .finally(function () {
       console.log("Promise running");
});



Post a Comment

Previous Post Next Post