Async — callbacks, promises, async/await

DarslarWeb dasturlash

Async — callbacks, promises, async/await

Vaqt oluvchi amallar: setTimeout, fetch va ularni kutish uchun 3 ta uslub.

60 daqiqa
JavaScript — Dars 18

Asinxron JavaScript

Server javobini kutish, timer, rasm yuklash — hammasi bu yerda. Callback → Promise → async/await evolyutsiyasi.

Promiseasyncawaitfetch

Dars rejasi

6 ta mavzu
  1. 01Sync va async farqi
  2. 02Callback
  3. 03Callback hell
  4. 04Promise
  5. 05async / await
  6. 06fetch bilan real API

1. Sync va async farqi

1// Sinxron — yuqoridan pastga ketma-ket
2console.log("1");
3console.log("2");
4console.log("3");
5// 1, 2, 3
6
7// Asinxron — kutish bor
8console.log("1");
9setTimeout(() => console.log("2"), 1000);
10console.log("3");
11// 1, 3, 2 ← 2 keyin chiqadi

2. Callback

Callback — boshqa funksiyaga argument sifatida berilgan funksiya. «Tayyor bo'lsang meni chaqir» degani.

1setTimeout(() => {
2 console.log("3 sekund o'tdi");
3}, 3000);
4
5// Custom callback
6function malumotOl(callback) {
7 setTimeout(() => {
8 const data = { ism: "Ali", yosh: 17 };
9 callback(data);
10 }, 1000);
11}
12
13malumotOl((natija) => {
14 console.log("Keldi:", natija);
15});

3. Callback hell

Callback hell — piramida
1userOl(id, (user) => {
2 postlarniOl(user.id, (postlar) => {
3 kommentOl(postlar[0].id, (kommentlar) => {
4 javobOl(kommentlar[0].id, (javoblar) => {
5 // ...chuqur va chuqur...
6 console.log(javoblar);
7 });
8 });
9 });
10});

4. Promise

Promise — kelajakdagi qiymatning «va'dasi». 3 ta holati bor: pending, fulfilled, rejected.

1const vada = new Promise((resolve, reject) => {
2 setTimeout(() => {
3 const muvaffaq = Math.random() > 0.3;
4 if (muvaffaq) {
5 resolve("Ma'lumot keldi");
6 } else {
7 reject("Xato yuz berdi");
8 }
9 }, 1000);
10});
11
12vada
13 .then((natija) => console.log("OK:", natija))
14 .catch((xato) => console.log("Xato:", xato))
15 .finally(() => console.log("Yakun"));
16
17// Ketma-ket zanjir
18fetch("/api/user")
19 .then(res => res.json())
20 .then(user => fetch("/api/posts/" + user.id))
21 .then(res => res.json())
22 .then(posts => console.log(posts))
23 .catch(err => console.error(err));

pending

Kutilmoqda — hali tugamagan.

fulfilled

resolve() chaqirildi — natija bor.

rejected

reject() chaqirildi — xato chiqdi.

5. async / await

Promise'larning toza, sinxron ko'rinishdagi yozuvi. ES2017'da kelgan eng yaxshi hadya.

Bir xil kod — 2 xil uslub
1// Then bilan
2function userOl() {
3 return fetch("/api/user")
4 .then(res => res.json())
5 .then(user => console.log(user));
6}
7
8// async/await bilan (ancha toza)
9async function userOl() {
10 const res = await fetch("/api/user");
11 const user = await res.json();
12 console.log(user);
13}
try/catch bilan xato ushlash
1async function malumotOl() {
2 try {
3 const res = await fetch("/api/user");
4 if (!res.ok) throw new Error("Status: " + res.status);
5 const user = await res.json();
6 return user;
7 } catch (err) {
8 console.error("Xato:", err.message);
9 return null;
10 }
11}

6. fetch bilan real API

1// GET so'rov
2async function postlariOl() {
3 const res = await fetch("https://jsonplaceholder.typicode.com/posts");
4 const postlar = await res.json();
5 return postlar.slice(0, 5);
6}
7
8// POST so'rov
9async function yangiPost(sarlavha, matn) {
10 const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
11 method: "POST",
12 headers: { "Content-Type": "application/json" },
13 body: JSON.stringify({ title: sarlavha, body: matn }),
14 });
15 return await res.json();
16}
17
18// Promise.all — parallel
19async function koplabOl() {
20 const [users, posts] = await Promise.all([
21 fetch("/api/users").then(r => r.json()),
22 fetch("/api/posts").then(r => r.json()),
23 ]);
24 return { users, posts };
25}
API'dan ma'lumot olish
Natijajonli

Kichik test

0 / 4

1.Promise'ning 3 ta holati?

2.await qaerda ishlaydi?

3.async funksiya nima qaytaradi?

4.Parallel bajarish uchun?

Mustaqil ish

0 / 6