w3resource

Wrapping Asynchronous operations in JavaScript Promises


Custom Promise Wrapper:

Write a JavaScript function that wraps an asynchronous operation in a Promise.

Solution-1: Wrapping setTimeout in a Promise

Code:

// Function to simulate an asynchronous operation using setTimeout
function asyncOperationWithTimeout(delay) {
  // Return a new Promise
  return new Promise((resolve, reject) => {
    // Simulate success or failure using a random boolean
    const isSuccess = Math.random() > 0.5;

    // Use setTimeout to simulate a delay
    setTimeout(() => {
      if (isSuccess) {
        resolve(`Operation succeeded after ${delay}ms`);
      } else {
        reject(new Error(`Operation failed after ${delay}ms`));
      }
    }, delay);
  });
}

// Test the custom Promise wrapper
asyncOperationWithTimeout(1000)
  .then((result) => console.log(result)) // Log success message
  .catch((error) => console.error(error)); // Log error message

Output:

"Operation succeeded after 1000ms"

Explanation:

  • Asynchronous Operation: Simulates a delay using setTimeout.
  • Random Outcome: Determines success or failure randomly.
  • Promise Handling:
    • Resolves with a success message if the operation is successful.
    • Rejects with an error if the operation fails.

Solution-2: Wrapping a Callback-Based API in a Promise

Code:

// Function to simulate an asynchronous file read operation
function fakeFileRead(fileName, callback) {
  // Simulate asynchronous delay
  setTimeout(() => {
    if (fileName === "valid.txt") {
      callback(null, "File content: Hello, World!");
    } else {
      callback(new Error("File not found"), null);
    }
  }, 1000);
}

// Promise wrapper for the fake file read function
function readFilePromise(fileName) {
  // Return a new Promise
  return new Promise((resolve, reject) => {
    // Call the callback-based function
    fakeFileRead(fileName, (err, data) => {
      if (err) {
        reject(err); // Reject the Promise with an error
      } else {
        resolve(data); // Resolve the Promise with the data
      }
    });
  });
}

// Test the custom Promise wrapper
readFilePromise("valid.txt")
  .then((content) => console.log(content)) // Log file content
  .catch((error) => console.error(error)); // Log error message

readFilePromise("invalid.txt")
  .then((content) => console.log(content)) // Log file content
  .catch((error) => console.error(error)); // Log error message

Output:

"File content: Hello, World!"
[object Error] { ... }

Explanation:

  • Callback-Based Function: A simulated file-reading operation that accepts a callback.
  • Promise Wrapper:
    • Converts the callback into a Promise.
    • Resolves with file content or rejects with an error.
  • Test Cases:
    • Reads a valid file successfully.
    • Handles an error for an invalid file

See the Pen promises-and-async-await-exercise-10 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Control Concurrent API Requests with JavaScript Throttling Techniques.
Next: JavaScript Promises with setTimeout Examples.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.