Skip to content

Instantly share code, notes, and snippets.

@PabloPenia
Last active September 6, 2022 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PabloPenia/65b3d07f527e1eb6248f082fd409c266 to your computer and use it in GitHub Desktop.
Save PabloPenia/65b3d07f527e1eb6248f082fd409c266 to your computer and use it in GitHub Desktop.
Fetch api
// ? FETCH API (uso basico)
// recurso = url del fecth / opciones es un objeto
// https://developer.mozilla.org/en-US/docs/Web/API/fetch
// https://www.youtube.com/watch?v=Kpn2ajSa92c
// * Hago la solictud
// fetch('recurso', {opciones})
// * si la respuesta es exitosa la capturo en la variable response (o el nombre que sea)
// * y la convierto a json o guardo en db, o lo que necesite hacer.
// .then(response => response.json())
// * capturo el json en la variable 'json' ( o el nombre que le de) y la logueo o lo q necesite...
// .then(json => console.log(json))
// * Si hay error lo capturo en el catch. y lo logueo
// .catch(error => console.log(error))
// * Ejemplos reales
function fetchSomething(url) {
fetch(url)
// IF el fetch es exitoso
.then((response) => response.json()) // convierto la respuesta a json
.then((json) => console.log(json)) // logueo respuesta o guardo en variable, etc.
// ELSE (hay un error en la consulta)
.catch((error) => console.log('Hay un error: ', error))
}
// * Lo mismo con async / await
async function fetchSomethingAsync(url) {
const response = await fetch(url)
// si hay un error se pueden ver en las propiedades 'ok' y 'status' del objeto response
// ej: response.ok === false . o response.status === 404.
// entonces si response.ok es falso HAY un error. Creo el error.
if (!response.ok) {
const message = `Ha ocurrido un error: ${response.status}`
// throw error ademas corta la ejecucion asincrona, que es lo que queremos si hay error.
throw new Error(message)
}
// si no hay error, no hace falta usar else ya q throw new error corta la ejecucion, entonces lo siguiente solo se ejecuta si NO hay error.
const respuestaFormateada = await response.json()
return respuestaFormateada
}
// * async / await con try catch
async function catchSomething(url) {
// aca cualquier codigo sincrono que neceste previo al fetch. Ej validando url sea un string:
if (typeof url !== 'string') {
throw new Error('La url es invalida.')
}
try {
const response = await fetch(url)
const json = await response.json()
// si necesito codigo sincrono despues d ela respuesta lo escribo sin await ej:
// const calcular = json.variable * 2 + 5
return console.log(json)
} catch (error) {
const message = `Ha ocurrido un error: ${error}`
throw new Error(message)
}
}
const demoUrl = 'https://jsonplaceholder.typicode.com/users/1'
// diferentes usos al llamar las funciones:
fetchSomething(demoUrl)
await fetchSomethingAsync(demoUrl)
await catchSomething(demoUrl)
// si las funciones no tuvieran manejo de errores puedo capturarlos asi tambien:
fetchSomethingAsync(demoUrl).catch((error) => console.log(error))
// o tambien hacer otro trabajo con la respuesta, en este caso por ej q ya tenemos manejos de errores en la funcion
// SABEMOS que no hay error si hay respuesta entonces puede ejecutar otros trabajos asi:
catchSomething(demoUrl).then (response => doSomething(response)
// o con await
const miRespuesta = await catchSomething(demoUrl)
doSomething(miRespuesta)
// Como saber cuando usar await? Logueo el tipo de la variable si retorna "Promise", es asincrono y hay q usar await.
// O cualquiera de las otras formas .then etc
console.log(typeof miVariable) // si retorna 'Promise' es asincrono.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment