回调函数

回调函数:一个函数作为参数需要依赖另一个函数执行调用。

这是它的英文解释:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

回调函数的一般形式:

//getData函数定义
function getData(callback){}

//getData 函数调用
getData(()=>{});         // 括号里是一个函数的定义

栗子1:

函数内部只有同步操作

function getData(callback){
    callback('123');
}
getData(function(n){
    console.log('callback函数被调用了')
    console.log(n);
})

栗子2:

getData函数内部有异步操作,那么在异步操作执行完成之后,就可以调用回调函数,并且把异步API执行的结果通过参数的形式传递给callback那么在getData里面的回调函数里面就能够拿到异步API执行的结果

function getMsg(callback){ //callback是一个形参
    setTimeout(function(){
        callback({                //在调用callback以后 将异步API执行的结果 通过参数的形式传递出来
            msg:'hello node.js'
        },2000)
    })
}

getMsg(function(data){ //function是一个实参是一个匿名函数 data用来接收异步API执行的结果
    console.log(data)
})

原文地址:https://www.cnblogs.com/wahaha-/p/14091434.html