How to use the Javascript Fetch API with Promises
January 16th 2024Summary
Many examples on the internet of the javascript fetch api use async and await. This is great, but sometimes its helpful to use promises instead. Here are some examples of how that is done.
The Code - Fetch with promises
Get
Javascript
function get(url) {
return fetch(url).then(response => response.json());
}
get("{someurl}")
.then(data => console.log(data))
.catch(e => console.error(e));
Put
Javascript
// PUT
function put(url,data) {
const body = {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
return fetch(url,body).then(response => response.json());
}
put("{someurl}",{data: ""})
.then(data => console.log(data))
.catch(e => console.error(e));
POST
Javascript
// POST
function post(url,data) {
const body = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
return fetch(url,body).then(response => response.json());
}
post("{someurl}",{data: ""})
.then(data => console.log(data))
.catch(e => console.error(e));
DELETE
Javascript
// DELETE
function remove(url) {
const body = {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
};
return fetch(url,body).then(response => response.json());
}
remove("{someurl}")
.then(data => console.log(data))
.catch(e => console.error(e));
The Code - Fetch with async and await
In the spirit of being thorough, here are the same functions using async and await.
Get
Javascript
// Get
async function get(url) {
const response = await fetch(url);
const json = await response.json();
return json;
}
Put
Javascript
// PUT
async function put(url,data) {
const body = {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
const response = await fetch(url,body);
const json = await response.json();
return json;
}
POST
Javascript
// POST
async function post(url,data) {
const body = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
const response = await fetch(url,body);
const json = await response.json();
return json;
}
DELETE
Javascript
// DELETE
async function remove(url) {
const body = {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
};
const response = await fetch(url,body);
const json = await response.json();
return json;
}