回调函数

152 阅读1分钟

不成立的情况

function add(x, y) {
  return x + y
}
add(10, 20)
console.log(1)
 // 不会等待
setTimeout(function () {
  console.log(2)
  console.log('hello')
 }, 0)  //最后执行

console.log(3)

function add(x, y) {
  console.log(1)
  setTimeout(function () {
	console.log(2)
    var ret = x + y
    return ret
  }, 1000)
	console.log(3)
	//到了这里就结束了 不会等待前面的定时器 所以就直接返回了默认值underfind
}
console.log(add(12,78))  //由于调用函数不会等待 所以ret是underfind

成立的情况

function add(x, y, callback) {
  console.log(1)
  setTimeout(function () {
    var ret = x + y
    callback(ret)
  }, 1000)
}

add(10, 20, function (ret) {
  console.log(ret)
})
回调函数获取异步函数内部操作的结果
// 注意:凡是需要得到一个函数内部异步操作的结果
//    setTimeout
//    readFile
//    writeFile
//    ajax
//   这种情况必须通过:回调函数