Saturday, November 9, 2024

JavaScript How to Define a Function that Returns a Promise


2. How to Define a Function that Returns a Promise
You can define a function to return a promise in two main ways: using a traditional promise with new Promise() or by defining the function as async.

Method 1: Using new Promise()
To create a promise manually, use the new Promise() constructor. Inside the constructor, define a callback function with two parameters, resolve and reject, which represent the success and failure outcomes of the promise, respectively.

Example:
function getData() {
  return new Promise((resolve, reject) => {
    const data = fetchData();  // Assume fetchData is a synchronous or async function

    if (data) {
      resolve(data);  // Promise is fulfilled successfully
    } else {
      reject('Data not found');  // Promise is rejected with an error
    }
  });
}

getData()
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error));

Method 2: Using async Functions
The async keyword simplifies promise-based code by implicitly returning a promise. Any function declared as async will automatically return a promise, and within the function, you can use await to pause execution until another promise resolves.

Example:
async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    return data;  // This will resolve the promise with data
  } catch (error) {
    throw error;  // This will reject the promise with the error
  }
}

getData()
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error));
Key Differences
  1. Manual Promise Creation (new Promise): Gives you control over the resolve and reject logic and is ideal if you need more complex or conditional async handling.
  2. async Function: Automatically returns a promise and is simpler to write and read, especially when chaining multiple asynchronous operations.

Summary
  • To check if a function returns a promise: Use instanceof or refer to documentation.
  • To define a function that returns a promise: Use either the new Promise() approach or declare the function with the async keyword.
Manual Creation of Promise
To create a promise manually, use the new Promise() constructor. Inside the constructor, define a callback function with two parameters, resolve and reject. The resolve and reject parameters in the new Promise() constructor are themselves callback functions.

Here’s how they work:

resolve: This function is called when the asynchronous operation completes successfully. Calling resolve(value) fulfills the promise with the specified value, which then becomes the resolved value of the promise. Any .then() attached to the promise will receive this value.

reject: This function is called if the asynchronous operation fails or if you want to handle an error condition. Calling reject(reason) marks the promise as rejected with the provided reason, typically an error message or error object. Any .catch() attached to the promise will handle this rejected state.

Example of resolve and reject as Callback Functions
In this example, resolve and reject are used as callbacks to indicate success or failure.
function checkNumber(num) {
  return new Promise((resolve, reject) => {
    if (num > 10) {
      resolve('Number is greater than 10');  // success case
    } else {
      reject('Number is 10 or less');       // failure case
    }
  });
}

// Using the promise
checkNumber(15)
  .then(message => console.log(message))   // Output: "Number is greater than 10"
  .catch(error => console.error(error));

checkNumber(5)
  .then(message => console.log(message))
  .catch(error => console.error(error));   // Output: "Number is 10 or less"

Why resolve and reject are Callback Functions
The resolve and reject functions are callbacks because they allow asynchronous code to "call back" into the promise to indicate the result of the operation. When you call either function, you’re "calling back" with either a success or failure result, and this triggers the corresponding .then() or .catch() handler on the promise.

So, resolve and reject are callback functions provided by the Promise constructor to control the outcome of the promise, depending on whether the operation succeeds or fails.

No comments:

Post a Comment

Hot Topics