【问题标题】:Callback function is not working in javascript回调函数在javascript中不起作用
【发布时间】:2019-01-25 23:09:14
【问题描述】:

我已经阅读了一些关于回调函数的文章。我理解他们是如何呈现的,比如添加 a + b 然后给出回调函数。但我也在做同样的事情。我首先声明了该函数然后再次调用它我调用了回调函数,为什么它在我的情况下不起作用?

function me(callback){
  console.log("1")
}
me(function(){ 
  console.log(2)
})

我期待console.log 1 然后是console.log 2。我只得到console.log 1

【问题讨论】:

  • “我调用回调函数” – 嗯……在哪里?!
  • 你没有调用callback()
  • 在console.log(1)之后调用回调;使用回调();

标签: javascript callback


【解决方案1】:

您正在调用callback 函数,它不会自动触发,这种方法是这样您可以在函数结束时使用该回调函数通知某事。

function me(callback) {
  console.log("1")

  // your process ended, lets notify
  callback();
}
me(function() {
  console.log(2)
})

【讨论】:

    【解决方案2】:

    您必须在作为参数传递给它的函数中实际调用回调函数:

    function me(callback){
      console.log(1)
      callback();
    }
    
    me(function(){ 
      console.log(2);
    })

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多