JavaScript中的回調(diào)函數(shù)是什么

這篇文章主要介紹了JavaScript中的回調(diào)函數(shù)是什么,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專(zhuān)注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、小程序開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了尖草坪免費(fèi)建站歡迎大家使用!

回調(diào)函數(shù)是每個(gè)前端程序員都應(yīng)該知道的概念之一?;卣{(diào)可用于數(shù)組、計(jì)時(shí)器函數(shù)、promise、事件處理中。

回調(diào)函數(shù)

首先寫(xiě)一個(gè)向人打招呼的函數(shù)。

只需要?jiǎng)?chuàng)建一個(gè)接受 name 參數(shù)的函數(shù) greet(name)。這個(gè)函數(shù)應(yīng)返回打招呼的消息:

function greet(name) {
  return `Hello, ${name}!`;
}

greet('Cristina'); // => 'Hello, Cristina!'

如果向很多人打招呼該怎么辦?可以用特殊的數(shù)組方法  array.map() 可以實(shí)現(xiàn):

const persons = ['Cristina', 'Ana'];

const messages = persons.map(greet);
messages; // => ['Hello, Cristina!', 'Hello, Ana!']

persons.map(greet) 獲取 persons 數(shù)組的所有元素,并分別用每個(gè)元素作為調(diào)用參數(shù)來(lái)調(diào)用 greet() 函數(shù):`greet('Cristina'), greet('Ana')。

有意思的是 persons.map(greet) 方法可以接受 greet()  函數(shù)作為參數(shù)。這樣 greet()  就成了回調(diào)函數(shù)。

persons.map(greet) 是用另一個(gè)函數(shù)作為參數(shù)的函數(shù),因此被稱(chēng)為高階函數(shù)

回調(diào)函數(shù)作為高階函數(shù)的參數(shù),高階函數(shù)通過(guò)調(diào)用回調(diào)函數(shù)來(lái)執(zhí)行操作。

重要的是高階函數(shù)負(fù)責(zé)調(diào)用回調(diào),并為其提供正確的參數(shù)。

在前面的例子中,高階函數(shù) persons.map(greet) 負(fù)責(zé)調(diào)用  greet()  函數(shù),并分別把數(shù)組中所有的元素 'Cristina'Ana ' 作為參數(shù)。

這就為識(shí)別回調(diào)提供了一條簡(jiǎn)單的規(guī)則。如果你定義了一個(gè)函數(shù),并將其作參數(shù)提供給另一個(gè)函數(shù)的話,那么這就創(chuàng)建了一個(gè)回調(diào)。

你可以自己編寫(xiě)使用回調(diào)的高階函數(shù)。下面是 array.map() 方法的等效版本:

function map(array, callback) {
  const mappedArray = [];
  for (const item of array) { 
    mappedArray.push(
      callback(item)    );
  }
  return mappedArray;
}

function greet(name) {
  return `Hello, ${name}!`;
}

const persons = ['Cristina', 'Ana'];

const messages = map(persons, greet);messages; // => ['Hello, Cristina!', 'Hello, Ana!']

map(array, callback) 是一個(gè)高階函數(shù),因?yàn)樗没卣{(diào)函數(shù)作為參數(shù),然后在其主體內(nèi)部調(diào)用該回調(diào)函數(shù):callback(item)。

注意,常規(guī)函數(shù)(用關(guān)鍵字 function 定義)或箭頭函數(shù)(用粗箭頭 => 定義)同樣可以作為回調(diào)使用。

同步回調(diào)

回調(diào)的調(diào)用方式有兩種:同步異步回調(diào)。

同步回調(diào)是“阻塞”的:高階函數(shù)直到回調(diào)函數(shù)完成后才繼續(xù)執(zhí)行。

例如,調(diào)用 map()greet() 函數(shù)。

function map(array, callback) {
  console.log('map() starts');
  const mappedArray = [];
  for (const item of array) { mappedArray.push(callback(item)) }
  console.log('map() completed');
  return mappedArray;
}

function greet(name) {
  console.log('greet() called');
  return `Hello, ${name}!`;
}

const persons = ['Cristina'];

map(persons, greet);
// logs 'map() starts'
// logs 'greet() called'
// logs 'map() completed'

其中 greet()  是同步回調(diào)。

同步回調(diào)的步驟:

  1. 高階函數(shù)開(kāi)始執(zhí)行:'map() starts'

  2. 回調(diào)函數(shù)執(zhí)行:'greet() called'

  3. .最后高階函數(shù)完成它自己的執(zhí)行過(guò)程:'map() completed'

同步回調(diào)的例子

許多原生 JavaScript 類(lèi)型的方法都使用同步回調(diào)。

最常用的是 array 的方法,例如: array.map(callback), array.forEach(callback), array.find(callback), array.filter(callback), array.reduce(callback, init)

// Examples of synchronous callbacks on arrays
const persons = ['Ana', 'Elena'];

persons.forEach(
  function callback(name) {    console.log(name);
  }
);
// logs 'Ana'
// logs 'Elena'

const nameStartingA = persons.find(
  function callback(name) {    return name[0].toLowerCase() === 'a';
  }
);
nameStartingA; // => 'Ana'

const countStartingA = persons.reduce(
  function callback(count, name) {    const startsA = name[0].toLowerCase() === 'a';
    return startsA ? count + 1 : count;
  }, 
  0
);
countStartingA; // => 1

字符串類(lèi)型的 string.replace(callback)  方法也能接受同步執(zhí)行的回調(diào):

// Examples of synchronous callbacks on strings
const person = 'Cristina';

// Replace 'i' with '1'
person.replace(/./g, 
  function(char) {    return char.toLowerCase() === 'i' ? '1' : char;
  }
); // => 'Cr1st1na'

異步回調(diào)

異步回調(diào)是“非阻塞的”:高階函數(shù)無(wú)需等待回調(diào)完成即可完成其執(zhí)行。高階函數(shù)可確保稍后在特定事件上執(zhí)行回調(diào)。

在以下的例子中,later() 函數(shù)的執(zhí)行延遲了 2 秒:

console.log('setTimeout() starts');
setTimeout(function later() {
  console.log('later() called');
}, 2000);
console.log('setTimeout() completed');

// logs 'setTimeout() starts'
// logs 'setTimeout() completed'
// logs 'later() called' (after 2 seconds)

later() 是一個(gè)異步回調(diào),因?yàn)?setTimeout(later,2000) 啟動(dòng)并完成了執(zhí)行,但是 later() 在 2 秒后執(zhí)行。

異步調(diào)用回調(diào)的步驟:

  1. 高階函數(shù)開(kāi)始執(zhí)行:'setTimeout()starts'

  2. 高階函數(shù)完成其執(zhí)行: 'setTimeout() completed'

  3. 回調(diào)函數(shù)在 2 秒鐘后執(zhí)行: 'later() called'

異步回調(diào)的例子

計(jì)時(shí)器函數(shù)異步調(diào)用回調(diào):

setTimeout(function later() {
  console.log('2 seconds have passed!');
}, 2000);
// After 2 seconds logs '2 seconds have passed!' 

setInterval(function repeat() {
  console.log('Every 2 seconds');
}, 2000);
// Each 2 seconds logs 'Every 2 seconds!'

DOM 事件偵聽(tīng)器還異步調(diào)用事件處理函數(shù)(回調(diào)函數(shù)的子類(lèi)型):

const myButton = document.getElementById('myButton');

myButton.addEventListener('click', function handler() {
  console.log('Button clicked!');
});
// Logs 'Button clicked!' when the button is clicked

4.異步回調(diào)函數(shù)與異步函數(shù)

在函數(shù)定義之前加上特殊關(guān)鍵字 async 會(huì)創(chuàng)建一個(gè)異步函數(shù):

async function fetchUserNames() {
  const resp = await fetch('https://api.github.com/users?per_page=5');
  const users = await resp.json();
  const names = users.map(({ login }) => login);
  console.log(names);
}

fetchUserNames() 是異步的,因?yàn)樗?async 為前綴。函數(shù)  await fetch('https://api.github.com/users?per_page=5') 從 GitHub 上獲取前5個(gè)用戶 。然后從響應(yīng)對(duì)象中提取 JSON 數(shù)據(jù):await resp.json()

異步函數(shù)是 promise 之上的語(yǔ)法糖。當(dāng)遇到表達(dá)式 await <promise>  (調(diào)用  fetch()  會(huì)返回一個(gè)promise)時(shí),異步函數(shù)會(huì)暫停執(zhí)行,直到 promise 被解決。

異步回調(diào)函數(shù)和異步函數(shù)是不同的兩個(gè)術(shù)語(yǔ)。

異步回調(diào)函數(shù)由高階函數(shù)以非阻塞方式執(zhí)行。但是異步函數(shù)在等待 promise(await <promise>)解析時(shí)會(huì)暫停執(zhí)行。

但是你可以把異步函數(shù)用作異步回調(diào)!

讓我們把異步函數(shù) fetch UserNames() 設(shè)為異步回調(diào),只需單擊按鈕即可調(diào)用:

const button = document.getElementById('fetchUsersButton');

button.addEventListener('click', fetchUserNames);

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“JavaScript中的回調(diào)函數(shù)是什么”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

網(wǎng)站題目:JavaScript中的回調(diào)函數(shù)是什么
本文來(lái)源:http://muchs.cn/article18/jopjgp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、全網(wǎng)營(yíng)銷(xiāo)推廣App設(shè)計(jì)、網(wǎng)站設(shè)計(jì)微信公眾號(hào)、面包屑導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司