🥕Writing a function that returns a promise

To write a function that returns a promise, you need to create a promise and return it from the function.

Here is an example of a function that returns a promise

function getData() {
  return new Promise((resolve, reject) => {
    // Perform an asynchronous operation
    setTimeout(() => {
      // If the operation succeeds, call resolve
      resolve('Success');
    }, 1000);
  });
}

getData().then(result => {
  // This function will be called when the promise is fulfilled
  console.log(result); // 'Success'
});

In this example, the getData function returns a promise that is fulfilled with the value 'Success' after 1 second (1000 milliseconds).

To return a promise from a function, you need to create the promise using the Promise constructor and return it from the function. You can then use the then and catch methods to handle the results of the promise.

Here is an example of a function that returns a promise that performs an HTTP request:

function getDataFromServer(url) {
  return new Promise((resolve, reject) => {
    // Perform an asynchronous operation
    fetch(url)
      .then(response => response.json())
      .then(data => {
        // If the operation succeeds, call resolve
        resolve(data);
      })
      .catch(error => {
        // If the operation fails, call reject
        reject(error);
      });
  });
}

getDataFromServer('https://example.com/data').then(data => {
  // This function will be called when the promise is fulfilled
  console.log(data);
});

In this example, the getDataFromServer function returns a promise that is fulfilled with the data returned from the server, or rejected with an error if the request fails.

Returning a promise from a function allows you to perform asynchronous operations and handle the results in a more organized

Last updated