Asynchronous fetch with first class functions and closures
Get and post with/without authorization needed
by Génesis García Morilla
JavaScript
// First class function with closure
const full_async_fetch = (obj = {}, url, data) =>
async function(url, data) {
if (data) {
obj.method = 'post'
obj.body = JSON.stringify(data)
} else {
delete obj.method
delete obj.body
}
const response = await fetch(url, obj)
if (response.ok) return await response.json()
else throw new Error(response.status)
}
// Asynchronous fetch with authorization
const async_autho_fetch = full_async_fetch({
headers: {
"Authorization": "Basic " +
btoa(sessionStorage.getItem('user') + ':' +
sessionStorage.getItem('pass'))
}
})
// Asynchronous fetch without authorization (public API)
const async_fetch = full_async_fetch()
// Get
async_fetch('https://httpbin.org/ip')
.then(data => document.body.innerHTML += `get ok ${JSON.stringify(data)}<br>`)
.catch(error => alert(error))
// Post
async_fetch('/echo/json/', {animal: 'dog'})
.then(data => document.body.innerHTML += 'post ok<br>')
.catch(error => alert(error))