JavaScript async and await: wait for the answer
Write await in front of fetch and json. try and catch hold the error.
All lessons · JavaScript lessons: learn from scratch
Wait for the answer
The server takes 1–2 seconds. If you do not wait, the result is undefined or a Promise. async is written at the start of the function. await goes only in front of fetch and json, and it does not let the next line run yet.
async function numune() {
const cavab = await fetch(url);
const melumat = await cavab.json();
}Send a question with async
The same request now sits inside a function. await stands in both places: fetch and json. The function does not run by itself. Call it by name at the end. The key still does not belong on the page.
const apiKey = "BURAYA_OZ_API_ACARINIZI_YAZIN";
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
async function aiSualGonder(sualMetni) {
const sorguMelumati = {
contents: [{ parts: [{ text: sualMetni }] }]
};
const cavab = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(sorguMelumati)
});
const melumat = await cavab.json();
const aiMetni = melumat.candidates[0].content.parts[0].text;
console.log(aiMetni);
}
aiSualGonder("JavaScript-də massiv nədir?");try and catch
The internet can drop, or the key can be wrong. The code that should run goes inside try. If there is an error, the program does not stop. catch runs instead.
async function tehlukesizSorgu(sual) {
try {
const cavab = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: sual }] }]
})
});
const melumat = await cavab.json();
console.log(melumat.candidates[0].content.parts[0].text);
} catch (xeta) {
console.log("Xəta baş verdi. İnterneti və açarı yoxla.");
}
}Questions
Why does await throw? The function has no async at the start. The two work together.
Why do you see a Promise? There is no await in front of cavab.json(). It is also required in front of fetch.
Why does the function not run? Writing it is not enough. Call aiSualGonder("sual") at the end.
What is the difference from .then()? async/await writes the same job line by line. The error is not a separate catch chain. try and catch hold it.