To convert a callback function to a promise in JavaScript, you can create a new Promise
object. Inside the promise, you call the original function with a callback that resolves or rejects the promise based on the result of the operation.
Here is an example of a callback function –
function fetchData(callback) {
setTimeout(() => {
const data = { message: "Hello, Codeymaze!" };
callback(null, data); // Simulating a successful response
}, 1000);
}
Now, let’s convert this to promise –
function fetchDataPromise() {
return new Promise((resolve, reject) => {
fetchData((error, data) => {
if (error) {
reject(error); // Reject the promise on error
} else {
resolve(data); // Resolve the promise with data
}
});
});
}
You can then use the fetchDataPromise
function like this –
fetchDataPromise()
.then(data => {
console.log(data); // { message: "Hello, Codeymaze!" }
})
.catch(error => {
console.error("Error:", error);
});
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order
- JavaScript – Add elements to a JSON ArrayIn JavaScript, you can add elements to a JSON array in several ways. Here are some common methods : Using push method The push() method in JavaScript… Read more: JavaScript – Add elements to a JSON Array
- JavaScript – Remove specific property from an objectTo remove a specific property from an object in JavaScript, you can use the delete operator or create a new object without those properties. Let’s explore some… Read more: JavaScript – Remove specific property from an object
- JavaScript – Convert an object to an arrayThere are many ways to convert an object to an array in JavaScript. Let’s explore some common approaches. Convert Object Values to Array If you… Read more: JavaScript – Convert an object to an array