async function load() { let result = await ez.request.get(url) }
In Asking a Server and in your chat you wrote await and async without knowing why. Here is why.
A server is another computer, maybe in another country. Your question travels there over the internet, the server looks up the data, and the answer travels back. That takes time: a tenth of a second on good wifi, a few seconds on bad wifi.
JavaScript does not wait by itself. It runs the next line right away. If the next line needs the answer, the answer is not there yet.
await says: stop here until the answer is back.
let result = await ez.request.get(url)
result.ok // true
result.body // the data
Without await, result is not the answer. It is only a note that says "the answer is coming". JavaScript calls that note a Promise. The note has no ok and no body:
let result = ez.request.get(url)
result.ok // undefined
result.body // undefined
So result.body.length stops your code with TypeError: Cannot read properties of undefined (reading 'length'). When you see undefined where the data should be, look for a missing await.
await only works inside a function that has async in front of it:
let temperatureText = ez.dom.select('#temperature').at(0)
async function loadWeather() {
let result = await ez.request.get(url)
temperatureText.textContent = result.body.at(-1).temperature
}
async tells JavaScript: this function waits for things inside it. Forget it, and you get this error:
SyntaxError: await is only valid in async functions and the top level bodies of modules
A SyntaxError means the code is written wrong, so no line of the script runs, not even the lines above the mistake. Read this one as: "you used await, so put async in front of the function".
The rule, short: await in front of the request, async in front of the function.
An async function takes time too, because it waits inside. If something must happen after it is done, put await in front of the call:
let updatedText = ez.dom.select('#updated').at(0)
async function refresh() {
await loadWeather()
updatedText.textContent = 'Updated'
}
The word Updated appears only after the weather is on the page. refresh uses await, so refresh needs async too.
When nothing has to wait for it, call it without await. The usual place is the last line of the script, which starts the page:
loadWeather()
Watch the order the lines run in:
async function loadWeather() {
console.log('1. asking the server')
let result = await ez.request.get(url)
console.log('3. got the answer')
}
loadWeather()
console.log('2. the script goes on')
The console shows 1, 2, 3. While loadWeather waits for the server, the rest of the script keeps going. That is why the page does not freeze while it waits: buttons still work and the page can still be scrolled.
In the chat project every function that talks to the server is async, and every request has await in front. async and await are plain JavaScript, not part of ez.