async/await क्या है
async/await आपको promise code ऐसे लिखने देता है कि यह ordinary top-to-bottom code जैसा पढ़ा जाए।
In this page:
Syntax
async function functionName() {
try {
const result = await promiseReturningCall();
} catch (err) {
// handle err
}
}
async/await
एक async function हमेशा एक promise return करता है। await function को तब तक pause करता है जब तक एक promise settle न हो, इसकी value return करते हुए या इसकी rejection throw करते हुए, जिसे आप try/catch से handle करते हैं। ES modules में Top-level await काम करता है।
Note:
await सिर्फ async function को pause करता है, पूरे program को नहीं।
उदाहरण: async/await
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
async function main() {
try {
const a = await delay(5, "first");
const b = await delay(5, "second");
console.log(a, b);
await Promise.reject(new Error("boom"));
} catch (e) {
console.log("caught:", e.message);
}
}
main();
// Output:
// first second
// caught: boom
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- await भूल जाना और एक Promise object पाना
- एक loop में await इस्तेमाल करना जब calls parallel में चल सकती हों
- try/catch भूल जाना
चैप्टर सारांश
- async functions promises return करते हैं
- await एक promise unwrap करता है
- errors के लिए try/catch इस्तेमाल करें
- await सिर्फ अपना function pause करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: