How to Convert Callback to Promise in JavaScript ?
Last Updated :
26 Mar, 2024
Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improve readability and maintainability.
Using the Promise constructor
This approach involves manually creating a promise around the asynchronous operation. It requires creating a new promise and resolving or rejecting it based on the outcome of the asynchronous operation.
Syntax:
function promisifiedFunction(arg1, arg2) {
return new Promise((resolve, reject) => {
myFunctionWithCallback(arg1, arg2, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});}
Example: In this, the promise-based function is used to fetch data from the API.
JavaScript
function fetchDataWithCallback(url, callback) {
setTimeout(() => {
const data = {
message: 'Data fetched successfully',
url: url
};
callback(null, data);
}, 1000);
function fetchDataPromise(url) {
return new Promise((resolve, reject) => {
fetchDataWithCallback(url, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
fetchDataPromise('https://api.example.com/data')
.then(data => console.log('Data:', data))
.catch(error => console.error('Error:', error));
Output:
OutputUsing a custom promise-based wrapper
This approach involves creating a custom wrapper function around the existing callback-based function.
Inside the wrapper function, a new promise is created, and the original function is called with a callback.
The promise is resolved or rejected based on the callback's result.
Syntax:
function promisifiedFunction(arg1, arg2) {
return new Promise((resolve, reject) => {
originalFunctionWithCallback(arg1, arg2, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});}
Example: In this, the promise-based function is used to fetch data from the API.
JavaScript
function fetchDataWithCallback(url, callback) {
setTimeout(() => {
const data = {
message: 'Data fetched successfully',
url: url
};
callback(null, data);
}, 1000);
}
function fetchDataPromise(url) {
return new Promise((resolve, reject) => {
fetchDataWithCallback(url, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
fetchDataPromise('https://api.example.com/data')
.then(data => console.log('Data:', data))
.catch(error => console.error('Error:', error));
Output:
Output
Similar Reads
Promise vs Callback in JavaScript In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work d
5 min read
How to Convert an Existing Callback to a Promise in Node.js ? Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
7 min read
How to access the Value of a Promise in JavaScript In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously. The value of a Promise can be accessed in JavaScript using the following methods. Table of
2 min read
How to convert an asynchronous function to return a promise in JavaScript ? In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:Â You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
3 min read
How to Create a Custom Callback in JavaScript? A callback is a function that executes after another function has been completed in JavaScript. As an event-driven language, JavaScript does not pause for a function to finish before moving on to the next task. Callbacks enable the execution of a function only after the completion of another, making
3 min read