什么是回调函数?

197 阅读1分钟

一个回调函数是一个被作为参数传递给另一个函数的函数,然后在外部函数中触发。回调函数经常是事件发生后,或者task完成后执行。

同步的回调函数

同步回调函数是立即执行的。比如 Array.prototype.map() 中的第一个参数就是一个同步的回调函数。

const nums = [1,2,3];
const printDoublePlusOne = n => console.log(2 * n + 1);
nums.map(printDoublePlusOne); // LOGS: 3, 5, 7

异步的回调函数

异步的回调函数是异步的运算完成后执行。比如 Promise.prototype.then() 就是一个例子:

const nums = fetch('https://api.nums.org'); // Suppose the response is [1, 2, 3]
const printDoublePlusOne = n => console.log(2 * n + 1);

nums.then(printDoublePlusOne); // LOGS: 3, 5, 7