js中回调函数的学习笔记

2019-07-15  本文已影响0人  唐人不自醉

回调函数是什么在学习之前还真不知道js回调函数怎么使用及作用了,下面本文章把我在学习回调函数例子给各位同学介绍一下吧,有需了解的同学不防进入参考。

回调函数原理:

我现在出发,到了通知你”
这是一个异步的流程,“我出发”这个过程中(函数执行),“你”可以去做任何事,“到了”(函数执行完毕)“通知你”(回调)进行之后的流程

例子

1.基本方法

<script language="javascript" type="text/javascript">
function doSomething(callback) {
// … 
// Call the callback
callback('stuff', 'goes', 'here');
} 
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
} 
doSomething(foo); 
</script>

或者用匿名函数的形式

<script language="javascript" type="text/javascript">
 function dosomething(damsg, callback){
  alert(damsg);
  if(typeof callback == "function") 
  callback();
 } 
dosomething("回调函数", function(){
  alert("和 jQuery 的 callbacks 形式一样!");
 }); 
</script>

小程序 回调函数的使用

// 声明 函数
  getProductList(getList, options) {
    let that = this;
    // options 是个对象
    ajax({
      url: api.getProsWithoutImage,
      param: options,
      showLoading: false
    }).then(res => {
      if (res.data.code === "1") {
        let list = res.data.list  // 非车产品列表
        if (list.length == 0) {
          wx.showModal({
            title: '温馨提示',
            content: '暂无上架产品!',
            showCancel: false
          })
        }
        getList(list)  // 回调函数 处理 数组
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.data.message,
          showCancel: false
        })
      }
    })
}


// 调用函数
    let options = { branchCode, type: "2", kind: "0" };
    this.getProductList((noCarProduct) => {
      if (noCarProduct.length) {
        this.setData({
          carProduction: carProduct,
          noCarProductions: noCarProduct,
          noThing: true
        })
      } else {
        this.setData({
          carProduction: carProduct,
          noCarProductions: noCarProduct,
          noThing: false  // 显示"空空如也"
        })
      }
    }, options)
上一篇下一篇

猜你喜欢

热点阅读