JavaScript – Convert callback to promise

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