JS中的回调函数的理解和使用方法

176 阅读2分钟

一. 回调函数的作用

js代码会至上而下一条线执行下去,但是有时候我们需要等到一个操作结束之后再进行下一个操作,这时候就需要用到回调函数。

二. 回调函数的解释

因为函数实际上是一种对象,它可以存储在变量中,通过参数传递给另一个函数,在函数内部创建,从函数中返回结果值”,因为函数是内置对象,我们可以将它作为参数传递给另一个函数,到函数中执行,甚至执行后将它返回,它一直被“专业的程序员”看作是一种难懂的技术。

回调函数的英文解释为:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
翻译过来就是:回调函数是一个作为变量传递给另外一个函数的函数,它在主体函数执行完之后执行。

三. 回调函数的使用方法

代码如下:

function a(callback){
   console.log("这是parent函数a");
   var m = 1;
   var n = 3;
  return callback(m,n);
 }

 function b(m,n){
   console.log("这是回调函数B");
   return m + n;
 }

var result = a(b);
console.log("result = "+ result);

/*常用格式*/
function jeep(callback){
   console.log("这是jeep");
   var m = 1;
   var n = 3;
  return callback(m, n);
}

var bmw = jeep(function(m, n){
    console.log("这是bmw:"+ m + n);
    return m + n
});
console.log("auto: "+ bmw);

/*精简代码*/
function a(callback){
  var m = '回调函数';
  callback(m + 'suc');
}

a(function(res){
   console.log(res);
})

执行顺序为:

这是parent函数a
这是回调函数B
result = 4
函数首先执行了主题函数a,之后调用了回调函数b,最后返回函数a的返回值。

VUE 方法中使用:

//request 请求方法
request: function (url, data, method, ret){
      wx.request({
          url: url,
          data: data,
          method: method,
          header: {
              'Content-Type': 'application/x-www-form-urlencoded'
          },
          success(res) {
                ret(res.data);
              //ret(name, sex);
          },
          fail(err){
                console.log("err//", err);
          }
      })
},

//回调函数请求
request(url, data, 'post', function(res){
    console.log(res.data)
});

/*
request(url, data, 'post', function(name, sex){
     console.log(name, sex)
});
*/

结束~