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

时间:2011-06-24 09:39:38

标签: javascript ajax callback call

我是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);
}

6 个答案:

答案 0 :(得分:111)

烨。函数引用就像任何其他对象引用一样,您可以将它们传递给您的内容。

这是一个更具体的例子:

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"

答案 1 :(得分:12)

另外,可以很简单:

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

答案 2 :(得分:10)

如果您使用Google javascript callback function example,则会获得Getting a better understanding of callback functions in JavaScript

这是如何做回调函数:

function f() {
    alert('f was called!');
}

function callFunction(func) {
    func();
}

callFunction(f);

答案 3 :(得分: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中的变量都有本地范围)。

答案 4 :(得分: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

答案 5 :(得分:0)

您可以像这样使用JavaScript CallBak:

    import pickle
    import json
    import random
    import tflearn
    import tensorflow
    import numpy
    import nltk
   from nltk.stem.lancaster import LancasterStemmer
   stemmer = LancasterStemmer()


 with open("intents.json") as file:
     data = json.load(file)

try:
   with open("data.pickle", "rb") as f:
       words, labels, training, output = pickle.load(f)
except:
  words = []
  labels = []
  docs_x = []
  docs_y = []

for intent in data["intents"]:
    for pattern in intent["patterns"]:
        wrds = nltk.word_tokenize(pattern)
        words.extend(wrds)
        docs_x.append(wrds)
        docs_y.append(intent["tag"])

    if intent["tag"] not in labels:
        labels.append(intent["tag"])

words = [stemmer.stem(w.lower()) for w in words if w != "?"]
words = sorted(list(set(words)))

labels = sorted(labels)

training = []
output = []

out_empty = [0 for _ in range(len(labels))]

for x, doc in enumerate(docs_x):
    bag = []

    wrds = [stemmer.stem(w.lower()) for w in doc]

    for w in words:
        if w in wrds:
            bag.append(1)
        else:
            bag.append(0)

    output_row = out_empty[:]
    output_row[labels.index(docs_y[x])] = 1

    training.append(bag)
    output.append(output_row)

training = numpy.array(training)
output = numpy.array(output)

with open("data.pickle", "wb") as f:
    pickle.dump((words, labels, training, output), f)

tensorflow.reset_default_graph()

net = tflearn.input_data(shape=[None, len(training[0])])
net = tflearn.fully_connected(net, 8) 
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
net = tflearn.regression(net)

model = tflearn.DNN(net) 

try:
   model.load("model.tflearn")
except:
   model.fit(training, output, n_epoch=1000, batch_size=8, 
   show_metric=True)
   model.save("model.tflearn")


def bag_of_words(s, words):
   bag = [0 for _ in range(len(words))]

   s_words = nltk.word_tokenize(s)
   s_words = [stemmer.stem(word.lower()) for word in s_words]

for se in s_words:
    for i, w in enumerate(words):
        if w == se:
            bag[i] = 1

return numpy.array(bag)


def chat():
   print("Start talking with the bot (type quit to stop)!")
   while True:
      inp = input("You: ")
      if inp.lower() == "quit":
          break

     results = model.predict([bag_of_words(inp, words)])[0]
     results_index = numpy.argmax(results)
     tag = labels[results_index]

     if results[results_index] > 0.8:
         for tg in data["intents"]:
             if tg['tag'] == tag:
                 responses = tg['responses']
         print(random.choice(responses))
     else:
        print("I didn't get that, please check the question and try 
 again.")


 chat()

或Java脚本承诺:

var a;

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


function1(function2);