回调函数

回调函数

简单来说,回调函数就是一个函数执行完以后才执行的函数。
更复杂的来说;

Simply put: A callback is a function that is to be executed after another function has 
finished executing — hence the name ‘call back’.
More complexly put: In JavaScript, functions are objects. Because of this, functions can 
take functions as arguments, and can be returned by other functions. Functions that do this are 
called higher-order functions. Any function that is passed as an argument is called a 
callback function.

为什么需要回调函数

javascript 是事件驱动的语言.这表示函数不会等待回复,javascript就会继续执行后面的函数。
看一个简单的例子:

function first(){
  console.log(1);
}
function second(){
  console.log(2);
}
first();
second();

就像你期待的,会打印如下结果:
在这里插入图片描述
一切好说,但第一个函数包含一些不能一下就会被执行的部分,比如调用API等,为了演示这个环节,我们先用setTimeout来举个例子;

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}
function second(){
  console.log(2);
}
first();
second();

不知道setTimeout用来干什么没有关系,只知道console.log(1)会延迟500秒以后执行.
结果如下:
在这里插入图片描述
虽然我们把first函数先执行,但结果显示的时候函数2首先被执行。

也许你会问为什么你要演示这个:
因为我们不能只因为调用循序的问题,就可以放心写在前面的函数一定要比后面的函数首先执行。
回调函数就是确保特定的函数被特定的函数后执行。

建立回调函数

function doHomework(subject) {
  alert(`Starting my ${subject} homework.`);
}

doHomework('math');
// Alerts: Starting my math homework.

现在我们加回调函数。

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}

doHomework('math', function() {
  alert('Finished my homework');
});

首先会跳出"starting my math homework",然后是"finished my homework".

有时候回调函数不会一直在调用函数内被定义,有时候会这样写;

function doHomework(subject,callback){
				console.log('do my '+subject+' homework');
				callback();
			}
			
			function finishHomework(){
				console.log('I have done all the homework');
			}
			
			doHomework('math',finishHomework);

实际的例子

// pages/third/third.js
const dayMap = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

Page({
  data: {
    weekWeather:[]
  },
  onLoad(){
    this.getWeekWeather()
  },

 onPullDownRefresh:function(){
  this.getWeekWeather(function stopRefresh(){    //使用了回调函数
    wx.stopPullDownRefresh();
  })
 },

  getWeekWeather(callback){
    wx.request({
      url: 'https://test-miniprogram.com/api/weather/future', 
      data: {
       time:new Date().getTime(),
       city:'深圳市'
      },
      success:res=>{
       var result=res.data.result;
       this.setWeekWeather(result);
      },
      complete:function(){    //API调用结束以后,使用了回调函数
        callback && callback();
      }
    })
  },

  setWeekWeather:function(result){
   let weekWeather=[];
   for(var i=0;i<7;i++){
    let date=new Date();
    date.setDate(date.getDate()+i);   //一种获取连续天数的好方法
    weekWeather.push({
      day:dayMap[date.getDay()],
      date: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,
      temp: `${result[i].minTemp}° - ${result[i].maxTemp}°`,
      iconPath:'/images/'+result[i].weather+'-icon.png'
    });
   }
   weekWeather[0].day='今天';
   this.setData({
     weekWeather:weekWeather
   })
  },

})

上面的例子是在写小程序的时候首先使用了获取天气的API,然后调用结束以后使用了回调函数来结束下拉刷新。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值