Incepand cu 2013 si sigur dupa 2017 toate browserele serioase suporta: promisiuni + fetch + functii arrow.
Desi am solutii echivalente in Svelte, care compileaza si adapteaza codul JavaScript si pentru browsere mai vechi, uneori prefer solutii js mai simple.
Solutia postata nu este o mare descoperire, dar o notez pentru mine (sa o gasesc cand am nevoie) si pentru cine mai cauta asa ceva.
O metoda simpla si eleganta pentru comunicarea cu serverul de web este conectare cu limitare timp de raspuns:
const fetchWithTimeout = (uri, options = {}, timeout = 5000) => {
const controller = new AbortController()
const config = { ...options, signal: controller.signal }
const timeoutHandler = setTimeout(() => {
controller.abort()
}, timeout)
return fetch(uri, config)
.then((response) => {
if (!response.ok) {
throw new Error(`${response.status}: ${response.statusText}`)
}
return response
})
.catch((error) => {
if (error.name === 'AbortError') {
throw new Error('Response timed out')
}
throw new Error(error.message)
}).finally(() => clearTimeout(timeoutHandler))
}
const promiseTimeoutFetch = async (url, method = "GET", data = null) => {
var ret = null
try {
var options = {
method: method,
headers: {
"Accept": 'application/json',
"Content-Type": "application/json"
}
}
if (data != null) {
options['body'] = JSON.stringify(data)
}
response = await fetchWithTimeout(url, options, 1500)
ret = await response.json()
} catch (e) {
ret = e.message
}
return ret
}
const getFetch = async (url) => { return promiseTimeoutFetch(url) }
const postFetch = async (url, data) => { return promiseTimeoutFetch(url, "POST", data) }
Trimit JSON catre server si serverul raspunde in format JSON.
Functiile care ma intereseaza in programul final sunt getFetch si postfetch si un exemplu de utilizare este:
(async () => {
var ret = null
ret = await getFetch('/test/1?a=100&b=200')
if (typeof (ret) != 'object') console.log("Err", ret)
else console.log("call 1 =", ret)
ret = await postFetch('/test/2?a=55&b=66', { a: 1, b: 2, c: "test C" })
if (typeof (ret) != 'object') console.log("Err", ret)
else console.log("call 2 =", ret)
})()
Comunicatia cu serverul depinde si de AbortController, care a fost implementata in browsere incepand cu Firefox 57, Edge 16, Chrome 66, …
Acum Firefox este la versiunea 99, Edge este la versiunea 100, iar Chrome la versiunea 102.