一、回调函数的概念

    将函数作为参数,传递给另一个函数调用,回调函数也叫做高阶函数(callback)。

    如果传入的函数没有函数名称,就叫做匿名回调函数。

    回调函数的弊端:

    大代码量的函数不断嵌套,会造成代码可读性变差,嵌套关系复杂,容易出错。

    二、回调函数对异步的应用

    异步顺序的问题,例如定时器函数:

    // function a() { // setTimeout(() => { // console.log(‘a’); // }, 1000); // } // function b() { // setTimeout(() => { // console.log(‘b’); // }, 500); // } // a(); // b(); // 输出顺序:b,a,希望输出a,b通过回调函数实现。 // function a(b) { // setTimeout(() => { // console.log(‘a’); // b(); // }, 1000); // } // function b() { // setTimeout(() => { // console.log(‘b’); // }, 500); // } // a(b);

    2.核心应用,获取异步操作的值

    // http://localhost/JS2204(2203)/week06/Day27_jsonp/code/taobao.php // 封装函数实现获取数据。 // function $ajax() { // let xhr = new XMLHttpRequest(); // xhr.open(‘get’, ‘http://localhost/JS2204(2203)/week06/Day27_jsonp/code/taobao.php‘, true); // xhr.send(); // xhr.onload = function() { // if (xhr.readyState === 4) { // return xhr.responseText; // } // } // } // console.log($ajax()); //获取不到数据,返回undefined,因为return不是$ajax的,是内部的onload事件的。 // function $ajax() { // let data = null; // let xhr = new XMLHttpRequest(); // xhr.open(‘get’, ‘http://localhost/JS2204(2203)/week06/Day27_jsonp/code/taobao.php‘, true); // xhr.send(); // xhr.onload = function() { // if (xhr.readyState === 4) { // data = xhr.responseText; // console.log(5); // } // } // console.log(6); // return data; // } // console.log($ajax()); //无法获取,xhr.responseText是异步。比return还要慢一拍。 function $ajax(callback) { let xhr = new XMLHttpRequest(); xhr.open(‘get’, http://localhost/JS2204(2203)/week06/Day27_jsonp/code/taobao.php, true); xhr.send(); xhr.onload = function() { if (xhr.readyState === 4) { callback(xhr.responseText); //xhr.responseText是实参,传递给回调函数的形参d,d接收到了数据。 } } } $ajax(function(d) { //整个函数当作参数传递给$ajax函数做参数,并且$ajax里面调用此函数。 console.log(d); });