To convert a callback-based API to a Promise-based API in JavaScript, you can wrap the callback-based function in a new function that returns a Promise. Here’s an example:
// Original callback-based function
function fetchData(callback) {
setTimeout(() => {
const data = "data from the API";
callback(data);
}, 1000);
}
// Wrapper function that returns a Promise
function fetchDataPromise() {
return new Promise((resolve) => {
fetchData((data) => {
resolve(data);
});
});
}
In this example, fetchData
is the original callback-based function, and fetchDataPromise
is a new function that returns a Promise. The fetchDataPromise
function uses the Promise
constructor to create a new Promise, and it passes a callback function to the constructor that calls the original fetchData
function. The resolve
the function is called inside the callback passed to fetchData
to fulfill the Promise with the data returned by the API.
Now, instead of using the callback-based function, you can use the Promise-based function as follows:
fetchDataPromise()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
In this example, the then
the method is called on the Promise returned by fetchDataPromise to handle the resolved value and the catch method is called to handle any errors that might occur.