2016-11-07 92 views
0

让我们想象,我有一些代码:写一个函数回调

var someString = ""; 
function do1(){ 
    doA(); 
    doB(); 
} 

function doA(){ 
    // some process that takes time and gets me a value 
    someString = // the value I got in prior line 

function doB(){ 
    //do something with someString; 
} 

什么是确保somestring由DOB定义尝试使用它的正确方法?我认为这是一种需要回调的情况,但我不确定如何设置它?

+2

究竟什么是“一些过程时间”?它是异步的,即函数在完成之前是否返回? – Ryan

+0

我想我有点困惑。我知道如果代码是异步的(例如使用ajax的东西),我会需要一个解决方案,但是在任何情况下doB都可以在doA之前执行,因为doA非常慢(即一些巨大的循环),或者代码总是一行一行地运行,除非一行是异步的? – COMisHARD

+0

好吧。如果它是异步的,它将不会逐行运行。如果您在doA()内部进行ajax调用,它很可能是异步的(不要将async设置为false)。如果doA()中有一个巨大的循环,它会将someString设置为doB()之前仍会运行的内容。但是如果发生大的循环,你可能想看看webworkers,这将允许你做多线程。 – Thomas

回答

1

通常,我已经通过回调参数解决了这个问题,如下面的代码。但是,我不知道这是否正确答案。在我的情况下,它做得很好。

var someString = ""; 
function do1(){ 
    doA(doB); 
} 

function doA(callback){ 
    // some process that takes time and gets me a value 
    someString = // the value I got in prior line 
    callback(); 
} 

function doB(){ 
    //do something with someString; 
} 
+1

'doA(function(){doB()});'可以简化为'doA(doB);' – Ouroborus

+0

哦谢谢! :)我不知道。我要解决它。 – Bakyuns

+0

我相信我可以很容易地接受并使用它。但我不明白。你介意告诉我更多关于这段代码的逻辑吗? – COMisHARD

0

我通常写这些函数可以使用或不使用回调函数来调用。只有在typeof callback === 'function'的情况下,才能通过调用callback函数来执行此操作。这允许包含回调的可能性的功能有点更通用。显然,对callback()的调用需要来自您正在执行的任何异步操作的回调。在以下示例中,setTimeout用作异步操作。

var someString = ""; 
 
    
 
function do1() { 
 
    doA(doB); //Call doA with doB as a callback. 
 
} 
 
    
 
function doA(callback) { 
 
    setTimeout(function() { 
 
     //setTimeout is an example of some asynchronous process that takes time 
 
     //Change someString to a value which we "received" in this asynchronous call. 
 
     someString = 'Timeout expired'; 
 
     //Do other processing that is normal for doA here. 
 

 
     //Call the callback function, if one was passed to this function 
 
     if (typeof callback === 'function') { 
 
      callback(); 
 
     } 
 
    }, 2000); 
 
} 
 
    
 
function doB() { 
 
    //do something with someString; 
 
    console.log(someString); 
 
} 
 

 
do1();

你可以,当然,做到这一点不使用全局变量:一个使用

function do1() { 
 
    doA(doB); //Call doA with doB as a callback. 
 
} 
 
    
 
function doA(callback) { 
 
    setTimeout(function() { 
 
     //setTimeout is an example of some asynchronous process that takes time 
 
     //Simulate a result 
 
     var result = 'Timeout expired'; 
 

 
     //Do other processing that is normal for doA here. 
 

 
     //Call the callback function, if one was passed to this function 
 
     if (typeof callback === 'function') { 
 
      callback(result); 
 
     } 
 
    }, 2000); 
 
} 
 
    
 
function doB(result) { 
 
    console.log(result); 
 
} 
 

 
do1();

0
function someFunctionA(callback){ 
    var someString = "modify me"; 
    callback(someString); 
} 

function someFunctionB(someString){ 
    // do something 
} 

function main() { 
    someFunctionA(somefunctionB); 
} 
相关问题