回调函数
简单来说,回调函数就是一个函数执行完以后才执行的函数。
更复杂的来说;
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,然后调用结束以后使用了回调函数来结束下拉刷新。