Trabajar con internet
Hasta ahora todos tus datos los escribiste tú mismo. Hoy le pides datos reales a un servidor en algún lugar del mundo.
Working with the internet
So far you typed all your own data. Today you ask a real server somewhere in the world for data.
fetch() le pide algo a una dirección de internet. La respuesta no llega al
instante —viaja por la red—, así que fetch devuelve una promesa:
algo que dice "todavía no tengo tu dato, pero te aviso cuando llegue".
Para esperar ese aviso se usa await, dentro de una función marcada
async.
fetch() asks an internet address for something. The answer does not arrive
instantly — it travels over the network — so fetch returns a
promise: something that says "I do not have your data yet, but I will let
you know when it arrives".
To wait for that notice you use await, inside a function marked
async.
Esa API pública es de GitHub, no necesita clave ni registro. Te devuelve un objeto —exactamente lo que aprendiste en el módulo anterior— con la información pública de una cuenta.
That public API belongs to GitHub, no key or sign-up needed. It returns an object — exactly what you learned in the earlier module — with that account's public information.
Junta esto con lo que ya sabes del DOM: en vez de console.log, escribe el
resultado directo en un elemento de la página.
Combine this with what you already know about the DOM: instead of
console.log, write the result directly into a page element.
fetch también sirve para enviar información, no solo
pedirla. Se hace pasando un segundo argumento con el método y los datos.
No hay una API pública segura para probar esto en vivo sin registrarte, así que acá va el patrón exacto que usarías, para que lo tengas a mano cuando te haga falta:
fetch also works for sending information, not just asking
for it. You do it by passing a second argument with the method and the data.
There is no safe public API to try this live without signing up, so here is the exact pattern you would use, to have on hand when you need it:
JSON.stringify() convierte tu objeto a texto —el
mismo JSON.parse al revés que viste guardando datos en localStorage—,
porque por la red solo viaja texto, nunca objetos de JavaScript directamente.
JSON.stringify() converts your object to text — the
reverse of the JSON.parse you saw when saving data to localStorage
— because only text travels over the network, never JavaScript objects directly.
fetch, promesas y async/await, mostrar el resultado
en el DOM, manejar errores con try/catch, y el patrón para enviar datos con
POST.
Con esto tienes las piezas para conectar tu página con el mundo real. Falta un último paso: juntar absolutamente todo en un juego completo.
fetch, promises and async/await, showing the
result in the DOM, handling errors with try/catch, and the pattern for sending
data with POST.
With this you have the pieces to connect your page to the real world. One last step remains: putting absolutely everything together into a complete game.