Promises and async/await
How JavaScript represents results that arrive later: promise states and chains, async/await and its microtasks, error handling, parallel work and combinators, cancellation with AbortController, and latest-only requests in UI.
This topic starts at Junior level.
What a promise is
hələ hazır olmayan nəticəni təmsil edən obyektdir: şəbəkə cavabı, taymer, faylın oxunması. Asinxron funksiya qəbul etmək əvəzinə dərhal promise qaytarır, sən isə ona reaksiyalar bağlayırsan.
Üç vəziyyət
- pending (gözləmədə): iş hələ bitməyib;
- fulfilled (yerinə yetirilib): iş dəyərlə bitib;
- rejected (rədd edilib): iş səbəblə uğursuz olub, adətən bu səbəb
Errorobyektidir.
Fulfilled və rejected birlikdə settled (yekunlaşmış) adlanır. Promise ən çoxu bir dəfə yekunlaşır. Bundan sonra onun vəziyyəti və dəyəri bir daha dəyişmir, resolve və ya reject-in sonrakı çağırışları isə nəzərə alınmır.
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
delay(500, "ready").then((value) => console.log(value)); // "ready" after 500 msnew Promise-ə ötürülən funksiya executor adlanır. O, konstruktorun içində sinxron icra olunur və iki funksiya alır: resolve və reject. Executor xəta atsa, promise həmin xəta ilə rədd edilir.
Reaksiyalar həmişə sonra işləyir
then callback-i heç vaxt sinxron işləmir, promise artıq yekunlaşmış olsa belə. O, kimi növbəyə düşür və cari sinxron kod bitəndən sonra icra olunur:
const done = Promise.resolve(42);
done.then((value) => console.log("then " + value));
console.log("sync");
// sync
// then 42"Həmişə asinxron" qaydası bütöv bir bug sinfini aradan qaldırır: callback-in məlumatın cache-də olub-olmamasından asılı olaraq gah dərhal, gah da sonra işləməsi problemini.
new Promise nə vaxt lazımdır
Nadir hallarda. fetch, response.json(), async funksiyalar və müasir API-lərin çoxu onsuz da promise qaytarır. new Promise yalnız callback və ya hadisə ilə işləyən API-ni bükmək üçündür, yuxarıda delay-in setTimeout-u bükdüyü kimi.
A is an object that stands for a result that is not ready yet: a network response, a timer, a file read. Instead of taking a , an asynchronous function returns a promise immediately, and you attach reactions to it.
Three states
- pending: the work has not finished;
- fulfilled: it finished with a value;
- rejected: it failed with a reason, usually an
Error.
Fulfilled and rejected together are called settled. A promise settles at most once. After that its state and value never change, and later calls to resolve or reject are ignored.
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
delay(500, "ready").then((value) => console.log(value)); // "ready" after 500 msThe function passed to new Promise is the executor. It runs synchronously, inside the constructor, and receives two functions: resolve and reject. If the executor throws, the promise is rejected with that error.
Reactions always run later
A then callback never runs synchronously, even when the promise is already settled. It is queued as a and runs after the current synchronous code has finished:
const done = Promise.resolve(42);
done.then((value) => console.log("then " + value));
console.log("sync");
// sync
// then 42This "always asynchronous" rule removes a whole class of bugs where a callback sometimes runs immediately and sometimes later, depending on whether the data was cached.
When you write new Promise
Rarely. fetch, response.json(), async functions and most modern APIs already return promises. new Promise is for wrapping an API that only offers callbacks or events, as delay wraps setTimeout above.
Chaining: then, catch and finally
then-in hər çağırışı yeni promise qaytarır. Bu yeni promise-in necə yekunlaşacağını callback-in nə etdiyi müəyyən edir:
- dəyər qaytarır → yeni promise həmin dəyərlə fulfilled olur;
- promise qaytarır → yeni promise onu izləyir, yəni zəncir gözləyir;
- xəta atır → yeni promise həmin xəta ilə rejected olur.
fetch("/api/user")
.then((response) => {
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
})
.then((user) => fetch("/api/teams/" + user.teamId))
.then((response) => response.json())
.then((team) => renderTeam(team))
.catch((error) => showError(error.message))
.finally(() => hideSpinner());Xətalar zəncirdə necə hərəkət edir
Rejection catch-ə (və ya then-in ikinci arqumentinə) çatana qədər bütün uğur handler-lərini ötürüb keçir. catch(fn) sadəcə then(undefined, fn) deməkdir. Handler adi qaydada qayıdırsa, zəncir bərpa olunur: növbəti then qaytarılan dəyəri alır. Zəncirin rejected qalmasını istəyirsənsə, xətanı yenidən at.
Promise.reject(new Error("offline"))
.then(() => console.log("not called"))
.catch((error) => {
console.log("caught: " + error.message);
return [];
})
.then((items) => console.log("items: " + items.length));
// caught: offline
// items: 0finally
finally(fn) hər iki nəticədə işləyir, heç bir arqument almır və ilkin dəyəri və ya xətanı olduğu kimi ötürür. İstisna: fn xəta atsa və ya rədd edilmiş promise qaytarsa, nəticəni bu yeni xəta əvəz edir. Onu təmizləmə işləri üçün işlət: spinner-i gizlətmək, kilidi açmaq.
Tez-tez edilən səhvlər
then-in içindəreturn-ü unutmaq: növbəti addımundefinedalır və daxili promise-i gözləmir.- Promise-i qaytarıb zənciri davam etdirmək əvəzinə
then-in içində yenithenyazmaq. fetch-in 404 və ya 500 cavabında rədd ediləcəyini gözləmək. O, yalnız şəbəkə xətasında rədd edilir; yuxarıdakı kimiresponse.ok-u özün yoxla.
Every call to then returns a new promise. What its callback does decides how that new promise settles:
- returns a value → the new promise is fulfilled with that value;
- returns a promise → the new promise follows it, so the chain waits;
- throws → the new promise is rejected with the error.
fetch("/api/user")
.then((response) => {
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
})
.then((user) => fetch("/api/teams/" + user.teamId))
.then((response) => response.json())
.then((team) => renderTeam(team))
.catch((error) => showError(error.message))
.finally(() => hideSpinner());How errors travel
A rejection skips every success handler until it reaches a catch (or the second argument of a then). catch(fn) is just then(undefined, fn). If the handler returns normally, the chain is recovered: the next then receives the returned value. To keep the chain rejected, rethrow.
Promise.reject(new Error("offline"))
.then(() => console.log("not called"))
.catch((error) => {
console.log("caught: " + error.message);
return [];
})
.then((items) => console.log("items: " + items.length));
// caught: offline
// items: 0finally
finally(fn) runs on both outcomes, receives no argument and passes the original value or error through unchanged. The exception: if fn throws or returns a rejected promise, that new error replaces the result. Use it for cleanup, such as hiding a spinner or releasing a lock.
Common mistakes
- Forgetting
returninsidethen: the next step receivesundefinedand does not wait for the inner promise. - Nesting
theninsidetheninstead of returning the promise and continuing the chain. - Expecting
fetchto reject on 404 or 500. It rejects only on network failures; checkresponse.okyourself, as above.
async/await: syntax over promises
ayrıca mexanizm yox, promise-lər üzərində qurulmuş sintaksisdir:
asyncfunksiya həmişə promise qaytarır:return valueonu fulfilled edir,throwisə rejected;await expressionpromise-in yekunlaşmasını gözləyir, sonra onun dəyərini qaytarır və ya səbəbini xəta kimi atır.
async function loadTeamName(userId) {
const userResponse = await fetch("/api/users/" + userId);
if (!userResponse.ok) throw new Error("HTTP " + userResponse.status);
const user = await userResponse.json();
const teamResponse = await fetch("/api/teams/" + user.teamId);
const team = await teamResponse.json();
return team.name;
}
loadTeamName(7).then((name) => console.log(name));Kod yuxarıdan aşağı oxunur, amma bu, əvvəlki bölmədəki promise zəncirinin eynisidir.
await funksiyanın qalan hissəsi ilə nə edir
İlk await-ə qədər olan kod çağırışın bir hissəsi kimi sinxron icra olunur. await-də funksiya dayandırılır: idarə çağırana qayıdır və o, pending vəziyyətində promise alır. Gözlənilən promise yekunlaşanda funksiyanın qalan hissəsi mikrotapşırıq kimi planlaşdırılır. Dəyər artıq hazır olanda da belədir: await null belə funksiyanı cari sinxron kod və ondan əvvəl növbəyə düşmüş mikrotapşırıqlar bitənə qədər saxlayır.
async function task() {
console.log("2: inside, before await");
await null;
console.log("4: after await");
}
console.log("1: before the call");
task();
console.log("3: after the call");Yalnız async funksiyanın özü dayanır. Proqramın qalan hissəsi işləməyə davam edir, ona görə də çağıranın növbəti sətri "4"-dən əvvəl çap olunur.
try/catch ilə xətalar
Rədd edilən await elə həmin sətirdə xəta atır, ona görə də adi try/catch/finally işləyir:
async function save(draft) {
setSaving(true);
try {
await api.saveDraft(draft);
} catch (error) {
showToast(error.message);
} finally {
setSaving(false);
}
}await yalnız async funksiyaların içində və ES modulların üst səviyyəsində yazıla bilər.
is syntax on top of promises, not a separate mechanism:
- an
asyncfunction always returns a promise:return valuefulfils it,throwrejects it; await expressionwaits for the promise to settle, then evaluates to its value or throws its reason.
async function loadTeamName(userId) {
const userResponse = await fetch("/api/users/" + userId);
if (!userResponse.ok) throw new Error("HTTP " + userResponse.status);
const user = await userResponse.json();
const teamResponse = await fetch("/api/teams/" + user.teamId);
const team = await teamResponse.json();
return team.name;
}
loadTeamName(7).then((name) => console.log(name));The code reads top to bottom, but it is still the same chain of promises as in the previous section.
What await does to the rest of the function
The code before the first await runs synchronously, as part of the call. At await the function is suspended: control returns to the caller, which gets a pending promise. When the awaited promise settles, the rest of the function is scheduled as a microtask. This happens even when the value is already available: await null still pauses until the current synchronous code, and the microtasks queued before it, have run.
async function task() {
console.log("2: inside, before await");
await null;
console.log("4: after await");
}
console.log("1: before the call");
task();
console.log("3: after the call");Only the async function itself pauses. The rest of the program keeps running, which is why the caller's next line logs before "4".
Errors with try/catch
A rejected await throws at that line, so ordinary try/catch/finally works:
async function save(draft) {
setSaving(true);
try {
await api.saveDraft(draft);
} catch (error) {
showToast(error.message);
} finally {
setSaving(false);
}
}await is allowed only inside async functions and at the top level of ES modules.
Error handling and unhandled rejections
catch promise-i görməlidir
try/catch rejection-u yalnız promise try-ın içində gözlənilirsə tutur:
async function getUser(id) {
try {
return fetchUser(id);
} catch (error) {
return null;
}
}return fetchUser(id) promise-i gözləmədən çölə verir. Funksiya try blokundan dərhal çıxır və promise sonra rədd ediləndə catch heç vaxt işləmir: rejection çağırana çatır. return await fetchUser(id) problemi həll edir. try-dan kənarda return await hiss olunan heç nəyi dəyişmir.
"Başlat və unut" çağırışları
Async funksiyanı await, return və ya .catch() olmadan çağırmaq onun xətalarını itirir:
button.addEventListener("click", () => {
saveDraft();
});saveDraft rədd edilsə, bunu heç nə emal etmir. .catch()-i işi başlatdığın yerdə əlavə et və ya handler-i async edib içində try/catch yaz.
Emal olunmamış rejection-lar
Promise rədd edilib və cari mikrotapşırıqlar icra olunandan sonra da onun handler-i yoxdursa, brauzer window üzərində unhandledrejection hadisəsi göndərir, DevTools isə "Uncaught (in promise)" yazır. Node.js-də default --unhandled-rejections=throw rejimi (v15-dən bəri) bunu tutulmamış istisnaya çevirir və process.on("unhandledRejection") handler-i yoxdursa, proses dayanır.
window.addEventListener("unhandledrejection", (event) => {
monitoring.capture(event.reason);
});Belə qlobal handler-i proqramın axışını idarə etmək üçün yox, xətaları qeydə almaq üçün işlət.
forEach gözləmir
async function saveAll(items) {
items.forEach(async (item) => {
await save(item);
});
console.log("all saved");
}forEach callback-in qaytardığı promise-lərə məhəl qoymur. Nəticədə "all saved" heç bir yadda saxlama bitməmiş çap olunur, uğursuz olanlar isə emal olunmamış rejection-a çevrilir. Onları bir-bir icra etmək üçün await ilə for...of, paralel icra etmək üçün isə await Promise.all(items.map(save)) yaz.
Kiçik qaydalar
Errorobyektləri ilə rədd et.reject("failed")-in stack trace-i olmur.catchistənilən dəyəri ala bilər.error.message-i oxumazdan əvvəlerror instanceof Erroryoxla (TypeScript-də parametrunknowntiplidir)..catch(() => {})bug-ları gizlədir. Xətanı yalnız faydalı bir şey edə biləcəyin yerdə tut: mesaj göstər, yenidən cəhd et, ehtiyat variantı işlət. Qalanını yuxarı ötür.
A catch has to see the promise
try/catch catches a rejection only if the promise is awaited inside the try:
async function getUser(id) {
try {
return fetchUser(id);
} catch (error) {
return null;
}
}return fetchUser(id) hands the promise out without waiting. The function leaves the try block at once, and when the promise rejects later, the catch never runs: the caller gets the rejection. return await fetchUser(id) fixes it. Outside a try, return await changes nothing you would notice.
Fire-and-forget calls
Calling an async function without await, return or .catch() throws its errors away:
button.addEventListener("click", () => {
saveDraft();
});If saveDraft rejects, nothing handles it. Attach .catch() where you start the work, or make the handler async and use try/catch inside.
Unhandled rejections
When a promise is rejected and has no handler after the current microtasks have run, browsers fire an unhandledrejection event on window, and DevTools logs "Uncaught (in promise)". In Node.js the default mode --unhandled-rejections=throw (since v15) turns it into an uncaught exception, which ends the process unless a process.on("unhandledRejection") handler exists.
window.addEventListener("unhandledrejection", (event) => {
monitoring.capture(event.reason);
});Use such a global handler for reporting, not for control flow.
forEach does not wait
async function saveAll(items) {
items.forEach(async (item) => {
await save(item);
});
console.log("all saved");
}forEach ignores the promises its callback returns, so "all saved" is logged before any save finishes and failed saves become unhandled rejections. Use for...of with await to run them one by one, or await Promise.all(items.map(save)) to run them in parallel.
Smaller rules
- Reject with
Errorobjects.reject("failed")has no stack trace. - A
catchcan receive any value. Checkerror instanceof Errorbefore readingerror.message(in TypeScript the parameter isunknown). .catch(() => {})hides bugs. Catch where you can do something useful: show a message, retry, fall back. Let everything else propagate.
Sequential vs parallel work and the Promise combinators
Hər await növbəti sətir işləməzdən əvvəl gözləyir, ona görə də ard-arda gələn iki await ardıcıl işləyir: ümumi vaxt iki sorğunun cəminə bərabərdir.
const user = await getUser(id);
const orders = await getOrders(id);getOrders-ə user lazım deyilsə, hər ikisini başlat və hər ikisini gözlə:
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);İndi ümumi vaxt təxminən ikisindən yavaş olanının vaxtı qədərdir. İş getUser(id) və getOrders(id) çağırılanda başlayır; Promise.all heç nəyi başlatmır, sadəcə gözləyir. Hər ikisini əvvəlcə çağırıb sonra gözləmək də (const a = getUser(id); const b = getOrders(id);) onları paralel işlədir. Amma sən hələ a-nı gözləyərkən b rədd edilsə, o rejection-u hələ heç nə emal etmir: brauzer emal olunmamış rejection barədə xəbər verir, Node.js isə prosesi dayandırır. Promise.all isə bütün input-lara handler-i eyni anda bağlayır.
Dörd kombinator
| Metod | Fulfilled olur | Rejected olur | Tipik istifadə |
|---|---|---|---|
Promise.all | hamısı fulfilled olanda: dəyərlər input ardıcıllığı ilə | ilk rejection-da | bütün nəticələr lazımdır |
Promise.allSettled | hamısı yekunlaşanda: hər input üçün { status, value } və ya { status, reason } | heç vaxt | bir-birindən asılı olmayan tapşırıqlar, hər nəticəni göstərmək |
Promise.race | ilk yekunlaşan fulfilled olarsa | ilk yekunlaşan rejected olarsa | ilk cavab, sadə timeout |
Promise.any | ilk fulfilled olanda | hamısı rədd ediləndə: errors massivi olan AggregateError | ehtiyat mənbələr, fallback |
Code review-da çıxan detallar
Promise.alltez uğursuz olur, amma heç nəyi ləğv etmir. Digər sorğular işləməyə davam edir, onların nəticəsi isə atılır. Onları dayandırmaq üçünAbortSignalötür (növbəti bölmə).Promise.raceilə yazılmış timeout sorğunu yox, yalnız gözləməni dayandırır.fetchüçünAbortSignal.timeout(ms)sorğunu həqiqətən bitirir.- Boş input:
Promise.all([])[]ilə fulfilled olur,Promise.any([])AggregateErrorilə rədd edilir,Promise.race([])isə həmişəlik pending qalır. - 500 elementlik
Promise.all(items.map(upload))500 sorğunu birdən başladır. Eyni vaxtda işləyən sorğuların sayını məhdudlaşdır, məsələn, partiyalarla:
async function inBatches(items, size, worker) {
const results = [];
for (let i = 0; i < items.length; i += size) {
const batch = items.slice(i, i + size);
results.push(...(await Promise.all(batch.map(worker))));
}
return results;
}Each await waits before the next line runs, so two awaits in a row are sequential: the total time is the sum of both requests.
const user = await getUser(id);
const orders = await getOrders(id);If getOrders does not need user, start both and wait for both:
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);Now the total is about the slower of the two. The work starts when getUser(id) and getOrders(id) are called; Promise.all starts nothing, it only waits. Calling both first and awaiting later (const a = getUser(id); const b = getOrders(id);) runs them in parallel too, but if b rejects while you are still awaiting a, nothing handles that rejection yet: the browser reports an unhandled rejection, and Node.js ends the process. Promise.all attaches handlers to every input at once.
The four combinators
| Method | Fulfils | Rejects | Typical use |
|---|---|---|---|
Promise.all | when all fulfil: values in input order | at the first rejection | every result is required |
Promise.allSettled | when all settle: { status, value } or { status, reason } per input | never | independent tasks, report each outcome |
Promise.race | if the first input to settle fulfils | if the first input to settle rejects | first response, simple timeouts |
Promise.any | at the first fulfilment | when all reject: AggregateError with an errors array | redundant sources, fallbacks |
Details that come up in reviews
Promise.allfails fast but cancels nothing. The other requests keep running and their results are dropped. To stop them, pass anAbortSignal(next section).- A
Promise.racetimeout only stops the waiting, not the request. Forfetch,AbortSignal.timeout(ms)really ends it. - Empty input:
Promise.all([])fulfils with[],Promise.any([])rejects with anAggregateError, andPromise.race([])stays pending forever. Promise.all(items.map(upload))over 500 items starts 500 requests at once. Limit concurrency, for example with batches:
async function inBatches(items, size, worker) {
const results = [];
for (let i = 0; i < items.length; i += size) {
const batch = items.slice(i, i + size);
results.push(...(await Promise.all(batch.map(worker))));
}
return results;
}Cancellation with AbortController and fetch
Promise-in cancel() metodu yoxdur: yaradılandan sonra o, öz-özünə yekunlaşır. Ləğv edə biləcəyin şey onun arxasındakı işdir. Veb platformada bunun aləti AbortController-dir: onun abort() metodu və signal xassəsi var, siqnalı isə onu dəstəkləyən API-lərə ötürürsən: fetch, addEventListener və Node.js-in bir çox API-si.
const controller = new AbortController();
fetch("/api/report", { signal: controller.signal })
.then((response) => response.json())
.then(showReport)
.catch((error) => {
if (error.name === "AbortError") return;
showError(error);
});
cancelButton.addEventListener("click", () => controller.abort());abort()-dan sonra fetch promise-i AbortError adlı DOMException ilə, ya da abort(reason)-a ötürdüyün səbəblə rədd edilir. Ləğv istifadəçiyə göstəriləcək xəta deyil, ona görə də onu catch-də ayır. Controller yalnız bir dəfə abort edir və sıfırlana bilmir: hər əməliyyat üçün yenisini yarat.
Timeout-lar və birləşdirilmiş siqnallar
AbortSignal.timeout(ms)müəyyən vaxtdan sonra özüTimeoutErrorilə abort edən siqnal qaytarır (Baseline, geniş əlçatandır; aprel 2024-dən bütün əsas brauzerlərdə var).AbortSignal.any([a, b])siqnallarından hər hansı biri abort edən kimi həmin siqnalın səbəbi ilə abort edir (mart 2024-dən bütün əsas brauzerlərdə var).
async function getJSON(url, signal) {
const signals = [AbortSignal.timeout(8000)];
if (signal) signals.push(signal);
const response = await fetch(url, { signal: AbortSignal.any(signals) });
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
}Öz funksiyalarını ləğv edilə bilən etmək
signal qəbul et, siqnal artıq abort olunubsa, dərhal dayan və onun abort hadisəsini dinlə:
function delay(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const id = setTimeout(resolve, ms);
signal?.addEventListener(
"abort",
() => {
clearTimeout(id);
reject(signal.reason);
},
{ once: true },
);
});
}Abort yalnız klient tərəfini dayandırır. Server-ə artıq çatmış POST yenə də emal oluna bilər, ona görə də yazma əməliyyatlarını təkcə abort() ilə yox, server tərəfində də qorumaq lazımdır (idempotency açarları, versiya yoxlaması).
A promise has no cancel() method: once created, it settles on its own. What you can cancel is the work behind it. The web platform's tool for that is AbortController: it has an abort() method and a signal that you pass to APIs that support it, such as fetch, addEventListener and many Node.js APIs.
const controller = new AbortController();
fetch("/api/report", { signal: controller.signal })
.then((response) => response.json())
.then(showReport)
.catch((error) => {
if (error.name === "AbortError") return;
showError(error);
});
cancelButton.addEventListener("click", () => controller.abort());After abort(), the fetch promise rejects with an AbortError DOMException, or with the reason you passed to abort(reason). A cancellation is not a failure to show the user, so filter it out in catch. A controller aborts only once and cannot be reset: create a new one for every operation.
Timeouts and combined signals
AbortSignal.timeout(ms)returns a signal that aborts by itself with aTimeoutError(Baseline widely available; in all major browsers since April 2024).AbortSignal.any([a, b])aborts as soon as any of its signals aborts, with that signal's reason (in all major browsers since March 2024).
async function getJSON(url, signal) {
const signals = [AbortSignal.timeout(8000)];
if (signal) signals.push(signal);
const response = await fetch(url, { signal: AbortSignal.any(signals) });
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
}Making your own functions abortable
Accept a signal, give up early if it is already aborted, and listen for its abort event:
function delay(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const id = setTimeout(resolve, ms);
signal?.addEventListener(
"abort",
() => {
clearTimeout(id);
reject(signal.reason);
},
{ once: true },
);
});
}Aborting stops the client side only. A POST that already reached the server may still be processed, so writes need server-side protection (idempotency keys, version checks), not just abort().
Race conditions in UI: only the latest request wins
Axtarış sahəsi hər dəyişiklikdə sorğu göndərir: r, re, rea, reac, react. Şəbəkə ardıcıllığı qorumur. rea sorğusu yavaş olsa və onun cavabı ən sonda gəlsə, input-da react yazıldığı halda siyahıda rea-nın nəticələri görünəcək. Təkcə debounce bunu düzəltmir: o, sorğuların sayını azaldır, amma yavaş cavab yenə də yenisini ötüb keçə bilər. Platformadakı search-race incident-i bunu işləyən tətbiqdə debug etməyə imkan verir.
Qayda belədir: cavabı yalnız son sorğuya aiddirsə tətbiq et.
1. Köhnəlmiş cavabları nəzərə alma
react.dev effektdə təmizləmə bayrağı (flag) işlətməyi tövsiyə edir:
useEffect(() => {
let ignore = false;
searchProducts(query).then((items) => {
if (!ignore) setResults(items);
});
return () => {
ignore = true;
};
}, [query]);query dəyişəndə React əvvəlki effektin cleanup funksiyasını çağırır, ona görə də köhnə cavab ən sonda gəlsə belə atılır.
2. Əvvəlki sorğunu ləğv et
Eyni quruluş AbortController ilə həm də trafikə və server resurslarına qənaət edir:
useEffect(() => {
const controller = new AbortController();
searchProducts(query, { signal: controller.signal })
.then(setResults)
.catch((error) => {
if (error.name !== "AbortError") setError(error);
});
return () => controller.abort();
}, [query]);3. Bu işi query kitabxanasına həvalə et
TanStack Query hər nəticəni öz queryKey-i altında saxlayır. Platformadakı "TanStack Query: the life of useQuery" turu (v5.107.1) bu yolu QueryObserver və Query vasitəsilə izləyir.
const { data, isPending, error } = useQuery({
queryKey: ["search", query],
queryFn: ({ signal }) => searchProducts(query, { signal }),
enabled: query.length > 1,
});Hər axtarış sözü ayrıca query-dir və komponent öz cari açarının yazısını oxuyur. Ona görə də gecikən rea cavabı rea yazısına düşür və react nəticələrini heç vaxt əvəz etmir. queryFn signal-ı ötürdüyü üçün query köhnələndə (out-of-date) və ya aktiv olmayanda sorğu abort olunur. Siqnal ötürülməsə, sorğu sona qədər işləyir və onun məlumatı cache-ə yazılır.
React-dən kənarda
function latestOnly(request) {
let controller = null;
return (...args) => {
controller?.abort();
controller = new AbortController();
return request(controller.signal, ...args);
};
}Eyni race route loader-lərdə, autosave-də və pagination-da da yaranır: köhnə asinxron nəticənin yenisindən sonra gələ biləcəyi hər yerdə.
A search box sends a request on every change: r, re, rea, reac, react. The network does not keep the order. If the request for rea is slow and its response arrives last, the list shows results for rea while the input says react. Debouncing alone does not fix it: it sends fewer requests, but a slow response can still overtake a newer one. The platform's search-race incident lets you debug this in a running app.
The rule: apply a response only if it belongs to the latest request.
1. Ignore stale responses
react.dev recommends a cleanup flag in the effect:
useEffect(() => {
let ignore = false;
searchProducts(query).then((items) => {
if (!ignore) setResults(items);
});
return () => {
ignore = true;
};
}, [query]);When query changes, React runs the cleanup of the previous effect, so the older response is dropped even if it arrives last.
2. Abort the previous request
The same shape with AbortController also saves bandwidth and server work:
useEffect(() => {
const controller = new AbortController();
searchProducts(query, { signal: controller.signal })
.then(setResults)
.catch((error) => {
if (error.name !== "AbortError") setError(error);
});
return () => controller.abort();
}, [query]);3. Let a query library own it
TanStack Query stores each result under its queryKey. The platform's tour "TanStack Query: the life of useQuery" (v5.107.1) follows this path through QueryObserver and Query.
const { data, isPending, error } = useQuery({
queryKey: ["search", query],
queryFn: ({ signal }) => searchProducts(query, { signal }),
enabled: query.length > 1,
});Every term is a separate query, and the component reads the entry for its current key, so a late rea response lands in the rea entry and never replaces the react results. Because queryFn passes on the signal, the request is aborted when the query becomes out-of-date or inactive. Without the signal, it runs to the end and its data is cached.
Outside React
function latestOnly(request) {
let controller = null;
return (...args) => {
controller?.abort();
controller = new AbortController();
return request(controller.signal, ...args);
};
}The same race appears in route loaders, autosave and pagination: wherever an older async result can arrive after a newer one.
Under the hood: microtask order, thenables, withResolvers
Mikrotapşırıq addımlarını saymaq
Hər reaksiya bir mikrotapşırıqdır. Promise-i başqa promise ilə resolve etmək (then-dən promise qaytarmaq, async funksiyada return somePromise, resolve(somePromise)) iki əlavə addım tələb edir: spesifikasiya əvvəlcə daxili promise-in then-ini çağıran job-u növbəyə qoyur və xarici promise-i yalnız həmin reaksiya yekunlaşdırır. Native promise-ə await isə onu birbaşa, bir addımda işlədir.
async function direct() {
return "direct";
}
async function wrapped() {
return Promise.resolve("wrapped");
}
wrapped().then((value) => console.log(value));
direct().then((value) => console.log(value));
Promise.resolve()
.then(() => console.log("tick 1"))
.then(() => console.log("tick 2"));
// direct, tick 1, tick 2, wrappedMüsahibələrdə belə tapmacaları sevirlər, amma production kodu iki müstəqil zəncirin arasında neçə tick olmasından heç vaxt asılı olmamalıdır. B-yə A lazımdırsa, onu zəncirlə və ya gözlə.
Thenable-lar
await, Promise.resolve() və then-dən qaytarılan dəyər then metodu olan istənilən obyekti (thenable) qəbul edir və həmin metodu mikrotapşırıqda çağırır. Müxtəlif kitabxanaların promise-ləri bir-biri ilə məhz belə işləyir. Bunun tərs tərəfi də var: then metodu olan hər obyekt promise kimi qəbul olunur. Belə obyekti async funksiyadan qaytarsan, onun then-i çağırılacaq, ona görə də promise olmayan obyektə then adlı metod vermə.
const task = {
then(resolve) {
resolve("done");
},
};
console.log(await task); // "done"Dövrdə await
for (const id of ids) await load(id) qəsdən ardıcıl işləyir. Hər addıma əvvəlkinin nəticəsi lazımdırsa və ya server-ə birdən çox sorğu göndərmək olmazsa, bu doğrudur; addımlar bir-birindən asılı deyilsə, səhvdir. ESLint-in no-await-in-loop qaydası səni bu seçimi açıq şəkildə etməyə məcbur edir. for await...of isə async generator-lar kimi async iterable-ları oxuyur.
Promise.withResolvers
Promise.withResolvers() { promise, resolve, reject } qaytarır. Promise-i yekunlaşdıran kod executor-dan kənarda yaşayanda lazım olur: hadisələr, növbələr, testlər. Mart 2024-dən bütün brauzerlərdə (Chrome 119, Firefox 121, Safari 17.4) və Node.js 22-də mövcuddur.
function nextMessage(socket) {
const { promise, resolve, reject } = Promise.withResolvers();
const controller = new AbortController();
const options = { signal: controller.signal };
socket.addEventListener("message", (event) => resolve(event.data), options);
socket.addEventListener("error", () => reject(new Error("socket error")), options);
return promise.finally(() => controller.abort());
}Promise.try(fn) (Baseline 2025) onun daha yeni qohumudur: fn-i sinxron çağırır və qaytarılan dəyəri, atılan xətanı və ya qaytarılan promise-i bir promise-ə çevirir.
Counting microtask hops
Each reaction is one microtask. Resolving a promise with another promise (returning a promise from then, return somePromise in an async function, resolve(somePromise)) costs two extra hops: the spec first queues a job that calls the inner promise's then, and only that reaction settles the outer promise. await on a native promise uses it directly, in one hop.
async function direct() {
return "direct";
}
async function wrapped() {
return Promise.resolve("wrapped");
}
wrapped().then((value) => console.log(value));
direct().then((value) => console.log(value));
Promise.resolve()
.then(() => console.log("tick 1"))
.then(() => console.log("tick 2"));
// direct, tick 1, tick 2, wrappedInterviewers like such puzzles, but production code must never depend on how many ticks separate two independent chains. If B needs A, chain or await it.
Thenables
await, Promise.resolve() and a value returned from then all accept any object with a then method (a thenable) and call that method in a microtask. That is how promises from different libraries work together. The flip side: any object with a then method is treated as a promise. Returning such an object from an async function calls its then, so do not give a non-promise object a method named then.
const task = {
then(resolve) {
resolve("done");
},
};
console.log(await task); // "done"await in loops
for (const id of ids) await load(id) is sequential by design. That is right when each step needs the previous result or the server must not get a burst of requests, and wrong when the steps are independent. ESLint's no-await-in-loop rule makes you decide explicitly. for await...of consumes async iterables, such as async generators.
Promise.withResolvers
Promise.withResolvers() returns { promise, resolve, reject }, for when the code that settles the promise lives outside an executor: events, queues, tests. It is available across browsers since March 2024 (Chrome 119, Firefox 121, Safari 17.4) and in Node.js 22.
function nextMessage(socket) {
const { promise, resolve, reject } = Promise.withResolvers();
const controller = new AbortController();
const options = { signal: controller.signal };
socket.addEventListener("message", (event) => resolve(event.data), options);
socket.addEventListener("error", () => reject(new Error("socket error")), options);
return promise.finally(() => controller.abort());
}Promise.try(fn) (Baseline 2025) is its newer sibling: it calls fn synchronously and turns a return value, a thrown error or a returned promise into one promise.
Interview tips
30 saniyəlik cavab. "Promise sonradan gələn nəticəni təmsil edir. O, pending vəziyyətindən bir dəfə və yalnız bir dəfə ya dəyərlə fulfilled, ya da səbəblə rejected vəziyyətinə keçir. then yeni promise qaytarır, ona görə də dəyərlər və xətalar zəncir boyunca aşağı axır. async/await eyni mexanizm üzərində sintaksisdir: await funksiyanı dayandırır və promise yekunlaşanda onu mikrotapşırıq kimi davam etdirir."
Gözlənilən suallar
- Bu kod nə çap edəcək? Sinxron kod,
thencallback-ləri,awaitvəsetTimeoutqarışığı. Addım-addım izah et: əvvəl sinxron kod, sonra növbə ardıcıllığı ilə mikrotapşırıqlar, sonra tapşırıqlar. Executor-un sinxron işlədiyini də qeyd et. Promise.all,allSettled,racevəanyarasında fərq nədir? Hər birinin nə vaxt fulfilled və rejected olduğunu de, konkret hal üçün birini seç: bir-birindən asılı olmayan widget-lərdən ibarət dashboard üçünallSettled, istifadəçi və icazələr olmadan açıla bilməyən səhifə üçünall.- Bu sorğular niyə yavaşdır? Bir-birindən asılı olmayan işlərin ardıcıl gözlənilməsi.
Promise.allvariantını göstər və eyni vaxtda işləyən sorğuların limitini xatırlat. - Sorğunu necə ləğv edirsən?
AbortControllervəsignal,AbortError-un ayrılması və promise-in özünün ləğv edilə bilmədiyi. - Köhnə axtarışın nəticələri görünür. Cavablar ardıcıllığı pozulmuş gəlir. Köhnəlmiş cavab bayrağı,
abort()və ya sorğuya görə açarlanan query kitabxanası ilə həll et. Təkcə debounce-un niyə kifayət etmədiyini izah et.
Bal itirdən səhvlər
await-in thread-i blokladığını demək. O, yalnız async funksiyanı dayandırır, event loop işləməyə davam edir.Promise.all-un promise-ləri paralel işlətdiyini demək. İş promise-lər yaradılanda artıq başlamışdı,allsadəcə gözləyir.async-in kodu fon thread-ində işlətdiyini demək. Promise-lərin işi yenə də main thread-də gedir; CPU-nu yükləyən iş üçün Web Worker lazımdır.try { return promise } catch {}vəforEach(async ...): hər ikisi xətaları itirir.
Senior səviyyəni göstərən məqamlar
Sintaksisdən yox, dizayndan danış: ləğvi kim idarə edir, komponent yalnız son nəticəni necə zəmanət altına alır, uğursuz sorğu yazma əməliyyatını təkrarlamadan necə yenidən göndərilir və production-da emal olunmamış rejection-lar harada qeydə alınır.
A 30-second answer. "A promise represents a result that arrives later. It is pending, then fulfilled with a value or rejected with a reason, exactly once. then returns a new promise, so values and errors flow down the chain. async/await is syntax over the same mechanism: await suspends the function and resumes it as a microtask when the promise settles."
Questions you are likely to get
- What does this code log? Mixed sync code,
thencallbacks,awaitandsetTimeout. Walk through it: synchronous code first, then microtasks in queue order, then tasks. Mention that an executor runs synchronously. - What is the difference between
Promise.all,allSettled,raceandany? Say when each fulfils and rejects, and pick one for a concrete case: a dashboard of independent widgets isallSettled, a page that needs user and permissions isall. - Why are these requests slow? Sequential awaits of independent work. Show the
Promise.allversion and mention concurrency limits. - How do you cancel a request?
AbortControllerandsignal, filteringAbortError, and the fact that a promise itself cannot be cancelled. - Results of an old search show up. Out-of-order responses. Fix with a stale-response flag,
abort()or a query library keyed by the query. Explain why a debounce alone is not enough.
Mistakes that cost points
- Saying
awaitblocks the thread. It suspends only the async function; the event loop keeps running. - Saying
Promise.allruns promises in parallel. The work was already started when the promises were created;allonly waits. - Saying
asyncmakes code run in a background thread. Promise work still runs on the main thread; CPU-heavy work needs a Web Worker. try { return promise } catch {}andforEach(async ...): both lose errors.
Senior signal
Talk about design, not syntax: who owns cancellation, how a component guarantees latest-only results, how a failed request is retried without duplicating a write, and where unhandled rejections are reported in production.
What to check when reviewing promises and async/await
Bu siyahını yazmadığın kodu review edəndə işlət: komanda yoldaşının pull request-i, kitabxananın issue tracker-indəki snippet və ya AI assistentin təklifi. Bu yoxlamaları etməsən, iz qoymadan itən xətalar, səbəbsiz yerə bir-birini gözləyən sorğular və yeni cavabların üstündən yazılan köhnə cavablar gözdən qaçacaq.
- Hər promise
awaitolunur, qaytarılır, ya da ona.catch()bağlanırmı? Click handler-də tək başına yazılmışsave();,items.forEach(async ...)və yatry { return fetchUser(id) }xətaları itirir: rejection-u heç bircatchgörmür.try-ın içindəreturn await,forEachəvəzinə isəfor...ofvə yaPromise.allgözlə. fetchkoduresponse.ok-u yoxlayırmı?fetchyalnız şəbəkə xətasında rədd edilir, ona görə də 404 və ya 500 cavabı uğurlu nəticə kimi emal olunur.- Hər
thencallback-i öz promise-ini qaytarırmı?returnolmasa, növbəti addımundefinedalır və daxili promise-i gözləmir. - Köhnə sorğunun cavabı yenisindən sonra tətbiq oluna bilərmi? Şəbəkə ardıcıllığı qorumur. Effekt hər prop dəyişəndə sorğu göndərirsə,
ignorebayrağını və ya cleanup-da abort edilənAbortController-i axtar. - Bir-birindən asılı olmayan sorğular ard-arda gözlənilirmi? Ard-arda gələn iki
await-in vaxtları toplanır.Promise.allgözlə, yüzlərlə element olanda isə eyni vaxtda işləyən sorğuların sayına limit də qoyulmalıdır. - Ləğv ləğv kimi emal olunurmu?
catchAbortError-u istifadəçiyə göstərmək əvəzinə ayırmalıdır, hər əməliyyata isə yeni controller lazımdır.Promise.raceilə yazılmış timeout yalnız gözləməni dayandırır,AbortSignal.timeout(ms)isə sorğunu həqiqətən bitirir. - Xətalar səssizcə gizlədilirmi?
.catch(() => {})bug-ları gizlədir,reject("failed")-in isə stack trace-i olmur. Xətanı yalnız kodun mesaj göstərə, yenidən cəhd edə və ya ehtiyat variantı işlədə bildiyi yerdə tut.
Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. Skip it and you let through errors that vanish without a trace, requests that wait for each other for no reason and old responses that overwrite new ones.
- Is every promise awaited, returned or given a
.catch()? A baresave();in a click handler,items.forEach(async ...)ortry { return fetchUser(id) }loses errors: nocatchsees the rejection. Expectreturn awaitinsidetry, andfor...oforPromise.allinstead offorEach. - Does
fetchcode checkresponse.ok?fetchrejects only on network failures, so a 404 or 500 goes down the success path. - Does every
thencallback return its promise? Withoutreturn, the next step getsundefinedand does not wait for the inner promise. - Can the response to an older request be applied after a newer one? The network does not keep the order. When an effect fetches on every prop change, look for an
ignoreflag or anAbortControlleraborted in the cleanup. - Are independent requests awaited one after another? Two
awaits in a row add up their times. ExpectPromise.all, with a concurrency limit when there are hundreds of items. - Is cancellation handled as cancellation?
catchshould filter outAbortErrorinstead of showing it, and every operation needs a new controller. APromise.racetimeout stops only the waiting;AbortSignal.timeout(ms)really ends the request. - Are errors silently swallowed?
.catch(() => {})hides bugs, andreject("failed")has no stack trace. Catch only where the code can show a message, retry or fall back.
Check your understanding
Practise this
Hands-on work that uses this topic.
Build Your Own X
Incident Simulator
System Design
Weekly Challenges
Frontend History
See it in real code
Guided tours through the source of real libraries that rely on it.