POST Request with JavaScript Promises
In javascript Promises are the new addition in ES6. These promises make it a lot easier to work with asynchronous tasks, like API calls.
See how to make an asynchronous call using Promises:
const promiseFetchCountries = () => {
return new Promise((resolve, reject) => {
fetch("https://restcountries.com/v3.1/all")
.then((response) => {
if (response.ok) {
return response.json();
} else {
reject("Failed to fetch data");
}
})
.then((data) => resolve(data))
.catch((error) => reject(error));
});
};
promiseFetchCountries()
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
The new Promise() object is initialized which takes a function with resolve and reject methods as an argument. These methods are used to mark the response as resolved (success) or reject (failed).
To wait for an asynchronous call, and to manipulate the output result, JavaScript promises come with changing methods like .then() and .catch() , these methods wait until the request is completed.