Callback Functions - Passing functions as arguments

 Callback Functions - Gudbinta Functions sida Doodaha

JavaScript waa luuqad aad u awood badan oo adeegsata habab kala duwan si ay u maareyso koodhka. Mid ka mid ah fikradaha muhiimka ah ee JavaScript waa callback functions ama "functions la soo celin karo," taasoo ah in function laga gudbin karo dood ahaan function kale.

Callback Functions
Callback Functions 

Waa maxay Callback Function?

Callback function waa function loo diraa function kale si loo isticmaalo markuu dhammaysto hawsha uu qabanayo. Tani waxay si gaar ah faa'iido ugu leedahay marka aan la macaamilayno xog ka timaada API, shaqooyinka asynchronous (kuwa aan isla markiiba dhammayn), ama xisaab xisaabeed adag.

Tusaale Fudud

Bal aan eegno tusaale fudud oo ah sida callback function u shaqeeyo:

function salaamMagac(magac, callback) {
    console.log("Salaan " + magac);
    callback();
}

function muujinDhameystir() {
    console.log("Hawl la dhammeeyay!");
}

salaamMagac("Ahmed", muujinDhameystir);

Sida Ay Tani U Shaqeyso:

  1. salaamMagac() waa function qaadanaya labo dood, magac iyo callback function.
  2. Wuxuu marka hore daabacayaa salaanta.
  3. Markaas kadib, wuxuu wacayaa function-ka callback, taasoo keenaysa in fariinta "Hawl la dhammeeyay!" la daabaco.

Callback Functions iyo Asynchronous JavaScript

JavaScript waxaa badanaa loo adeegsadaa howlo socda, sida helitaanka xogta server-ka. Haddii function uu sugayo xog ama uu qabsanayo shaqo waqti qaadanaysa, waxaa fiican in loo isticmaalo callback function. Tusaale ahaan, isticmaalka setTimeout:

console.log("Shaqada waa bilaabatay");

setTimeout(function() {
    console.log("3 ilbiriqsi kadib shaqo waa dhamaatay");
}, 3000);

console.log("Sug... shaqadu way socotaa");

Waxaad arki doontaa:

  1. "Shaqada waa bilaabatay" ayaa markiiba la daabacayaa.
  2. "Sug... shaqadu way socotaa" ayaa sidoo kale markiiba muuqanaysa.
  3. Kadib 3 ilbiriqsi, "3 ilbiriqsi kadib shaqo waa dhamaatay" ayaa soo muuqanaysa.

  4. Callback Functions
    Callback Functions 

Maxay Tahay Faa'iidada Callback Functions?

  • Xakamaynta Asynchronous Code – Waxa ay ka hortagtaa in code-kaaga xannibo wax kale oo dhacaya.
  • Xirfad Sare – Waxay kuu oggolaaneysaa inaad si sahlan u maareyso xakamaynta howlo badan oo wada socda.
  • Dib u isticmaalid – Waxaad yeelan kartaa functions la isticmaali karo marar badan oo aan wax badan laga beddelin.

Gunaanad

Callback functions waa wax aad muhiim ugu ah JavaScript. Waxay kuu suurtagelinayaan in aad xakameyso functions-ka aad isticmaaleyso, khaasatan marka aad la macaamilayso xog dib uga soo laabaneysa server ama howlaha waqtiga qaata. Haddii aad si fiican u fahanto sida loo isticmaalo callback functions, waxaad si sahlan ugu xakamayn kartaa koodhkaaga si waxtar leh.

Hadda isku day inaad abuurto callback function kuu gaar ah oo aad la tijaabiso! 😊

Previous Post Next Post

Important

Important