如何将回调作为参数传递给另一个函数


83

我是ajax和回调函数的新手,如果我弄错了所有概念,请原谅我。

问题:我可以将回调函数作为参数发送给将执行该回调的另一个函数吗?

function firstFunction(){
    //some code

    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

function secondFunction(var1, var2, callbackfunction) {
    params={}
    if (event != null) params = event + '&' + $(form).serialize();

    // $.post() will execute the callback function
    $.post(form.action,params, callbackfunction);
}

Answers:


125

对。函数引用与任何其他对象引用一样,您可以将它们传递到您的内心。

这是一个更具体的示例:

function foo() {
    console.log("Hello from foo!");
}

function caller(f) {
    // Call the given function
    f();
}

function indirectCaller(f) {
    // Call `caller`, who will in turn call `f`
    caller(f);
}

// Do it
indirectCaller(foo); // alerts "Hello from foo!"

您还可以传递以下参数foo

function foo(a, b) {
    console.log(a + " + " + b + " = " + (a + b));
}

function caller(f, v1, v2) {
    // Call the given function
    f(v1, v2);
}

function indirectCaller(f, v1, v2) {
    // Call `caller`, who will in turn call `f`
    caller(f, v1, v2);
}

// Do it
indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3"


13

另外,可能很简单,例如:

if( typeof foo == "function" )
    foo();


2

是的,当然,函数是对象并且可以传递,但是您必须声明它:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

有趣的是,您的回调函数还可以访问您可能在firstFunction()中声明的每个变量(javascript中的变量具有局部作用域)。


0

示例CoffeeScript

test = (str, callback) ->
  data = "Input values"
  $.ajax
    type: "post"
    url: "http://www.mydomain.com/ajaxscript"
    data: data
    success: callback

test (data, textStatus, xhr) ->
  alert data + "\t" + textStatus

->javascript是什么意思?@ nothing-special-here
shenkwen

->只是正常功能。 var test = function(str, callback) { ajax call }
BarryMode

@shenkwen细箭头->是CoffeeScript语法,而不是JavaScript,当编译为JavaScript时,其简单含义是普通的JavaScript函数。JavaScript具有类似的箭头功能w3schools.com/Js/js_arrow_function.asp
布赖恩(Bryan)

0

您可以像这样使用JavaScript CallBak:

var a;

function function1(callback) {
 console.log("First comeplete");
 a = "Some value";
 callback();
}
function function2(){
 console.log("Second comeplete:", a);
}


function1(function2);

或Java脚本承诺:

let promise = new Promise(function(resolve, reject) { 
  // do function1 job
  let a = "Your assign value"
  resolve(a);
});

promise.then(             

function(a) {
 // do function2 job with function1 return value;
 console.log("Second comeplete:", a);
},
function(error) { 
 console.log("Error found");
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.