Kisa `async/await` ye e kijan li diferan de `.then()`?
asked 5 months ago124 viewsht
Mwen wè de fason pou ekri kòd asenkron:
fetch(url).then(r => r.json()).then(data => console.log(data));
ak
const r = await fetch(url);
const data = await r.json();
Èske se menm bagay la? Kiyès mwen ta dwe itilize?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
3 Answers
Wi, se menm bagay la anba kapo a: async/await se yon fason pi pwòp pou ekri kòd ki itilize Promise. await jis tann Promise la fini epi ba ou rezilta a.
Diferans prensipal yo:
1. Lizibilite: await fè kòd la li tankou kòd nòmal, liy pa liy. 2. Jesyon erè: ak await ou itilize try/catch:
async function chaje() {
try {
const r = await fetch(url);
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return await r.json();
} catch (err) {
console.error('Erè:', err);
}
}
3. Ou ka sèvi ak await sèlman anndan yon fonksyon async (oswa nan tèt yon modil ES).
Konsèy: itilize async/await pa defo. Kenbe .then() pou ti chèn kout.
Sign in to tell others whether this worked.
Fè atansyon pou pa mete await youn apre lòt lè rekèt yo pa depann youn sou lòt. Sa fè yo kouri an seri, e li pi dousman. Itilize Promise.all:
const [users, posts] = await Promise.all([getUsers(), getPosts()]);Sign in to tell others whether this worked.
Yon lòt bagay pou konnen: yon fonksyon async toujou retounen yon Promise, menm si w retounen yon valè senp. Kidonk moun ki rele l la dwe itilize await oswa .then() tou.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.