Ballanqaadka (Promise) JavaScript waa shay matalaya guusha ama fashilka hawl asyncronous ah (hawl aan si toos ah loo maamulin). Waxa uu ka caawiyaa in laga fogaado "callback hell" oo uu xasiliyo koodhka asyncronous-ka ah, taasoo ka dhigaysa mid fudud oo la akhrin karo.
![]() |
Promises - Creating and Handling Promises |
Promise waa object JavaScript ah oo matalaya hawl la sugayo inay fulanto mustaqbalka. Waxaa loo isticmaalaa in lagu maareeyo hawlaha asyncronous-ka ah si looga fogaado dhibaatada callback hell, taas oo ah marka la isticmaalo functions badan oo isku xiran (nested callbacks), taasoo keenaysa in koodhku adkaado in la fahmo.
Promise wuxuu leeyahay saddex xaaladood oo kala ah:
- Pending – Marka la abuuro, wali ma fulmin mana fashilmin.
- Fulfilled – Marka hawshii la sugayay ay guulaysato.
- Rejected – Marka hawshii la sugayay ay fashilanto.
Sida loo abuuro Promise
Promise waxaa la abuurayaa adigoo adeegsanaya constructor-ka Promise()
. Waxay qaadataa hal function oo leh laba parameters:
resolve
– Waa function la waco haddii hawshu ay guulaysato.reject
– Waa function la waco haddii hawshu ay fashilanto.
Tusaale ahaan, aan abuurno promise fudud oo simulating ah hawl waqti qaadanaysa:
Sida loo maareeyo Promise
Si aad u maareyso Promise, waxaa loo adeegsadaa .then()
iyo .catch()
.
.then()
– Waxaa lagu maareeyaa natiijada (fulfilled) ee Promise-ka..catch()
– Waxaa lagu qabtaa qaladaadka haddii Promise-ka uureject
noqdo.
Tusaale:
Sida loo isticmaalo multiple Promises
Mararka qaar, waxaad rabtaa inaad la tacaasho dhowr Promise isku mar. Waxaa jira dhowr farsamo oo loo adeegsado sida:
- Promise.all() – Waxaa la sugayaa dhammaan promises inay dhamaadaan.
- Promise.race() – Waxaa la sugayaa promise-kii ugu horreeyay ee dhammaada, xitaa haddii ay tahay
reject
. - Promise.allSettled() – Waxaa la sugayaa dhammaan promises si loo arko natiijo kasta.
- Promise.any() – Waxaa la sugayaa mid ka mid ah promises-ka oo guuleysta.
Tusaale:
Gabagabo
Promises waa hab aad muhiim u ah oo lagu maareeyo xogta asyncronous-ka ah ee JavaScript. Waxay yareeyaan dhibaatada callback hell waxayna fududeeyaan koodhka. Adeegsiga .then()
, .catch()
, iyo multiple Promises sida Promise.all()
waxay kaa caawinayaan inaad si hufan ula tacaasho xogta.
Haddii aad rabto inaad kor u qaaddo xirfaddaada JavaScript, barashada Promises waa tallaabo muhiim ah!