在javascript中使用callback之后解释输出

我是新来的JavaScript,我想了解callback。 我无法理解20为什么会在10之前打印出来。我的理解是对于一个callback函数,例如func1(parameter,func2())func2()是callback函数, func1执行“参数“传给func1 。 我的理解是正确的吗?

 function timePass(length){ console.log("finished after doing timePass for "+length +" seconds") } timePass(10,timePass(20)); 

以下输出:

完成时间通过20秒后完成

完成时间通过10秒后完成

这是因为你执行函数timePass然后 – 将结果添加为参数2。

解释发生了什么事情:

首先定义新function“timePass”,在控制台上打印function。
第二你执行timePass(10, /*But here you execute it again*/ timePass(20))

函数timePass(20)将首先执行,因为您已添加()
() == execute 。 如果您只是传递函数的名称,它将作为函数传递。 当你使用()它将被执行,然后结果将作为parameter passing。

使用回叫的例子

 function timePass(length, callbackFunction){ console.log("finished after doing timePass for "+length +" seconds"); // check if the function caller is included callback parameter // and check if it is function - to prevent errors. if (callbackFunction && typeof callbackFunction == "function") { // Execute the callback (timePass) callbackFunction(20); } } // Here you say, Execute timePass with arg 10, and then call timePass timePass(10, timePass); // and now callbackFunction defined above will be == timePass // You can do also timePass(10, anotherFunction) // So another function will be executed after console.log() 

用例

我们使用asynchronous代码时,大多数时候使用callback。

例如: Jsfiddle

 // Imagine we have function which will request the server for some data. function getData(index) { // The request - response will took some time // 0.1s ? 15s ? We don't know how big is the data we downloading. var data; // Imagine this is an AJAX call, not timeout. setTimeout(function() { // after 30ms we recieved 'server data' data = 'server data'; },30) return data; } var users = getData('users'); console.log(users); // undefined - because we returned "data" before the AJAX is completed. /* So we can change the function and adding an callback. */ function getAsyncData(index, callback) { var data; // Imagine this is an AJAX call, not timeout. setTimeout(function() { // after 30ms we recieved 'server data' data = 'server data'; callback(data); },30) } getAsyncData('users', function(data) { console.log(data); // 'server data' }); // OR function processData(data) { console.log(data); } getAsyncData('users', processData); // processData also logs 'server data' 

你并没有真正创build一个callback函数,而是在最后一行代码之前调用timePass(20)。

要传递一个callback函数,你应该这样做:

 function timePass(length,callback){ console.log("finished after doing timePass for "+length +" seconds") if(typeof(callback) == "function") callback(20); } timePass(10,timePass); 

基本上当解释者正在看这个时,它会调用timepass(20)来评估结果(这是什么也没有,因为你没有返回返回的东西),然后它试图进入外部函数。

 doFunction( doSomethingElse() ); 

如果doSomethingElse返回1,则必须先评估它才能将该1传递给doFunction

从根本上说,你实际上没有通过callback,你已经调用了函数。 也许你的意思是:

 callback = function() { somecode; } target = function(data, callback) { console.log('hi'); callback(); } target(10, callback); 

注意缺less()callbackcallback()