2012-10-06 69 views
0

可能吗?这个怎么做?点击按钮时,我打电话给function1。如果条件为真(i==1),则function1会暂停,并且仅在function2完全执行后才会执行以下代码。例如:Javascript - 通话功能2内功能1,然后继续

function1(i){ 
    //some code here 
    if(i == 1){ 
     function2(i); // call function2 and waits the return to continue 
    } 
    //the following code 
} 

function2(i){ 
    //do something here and returns 
} 
+3

让你觉得JavaScript是不确定性... ??? – perilbrain

+2

函数function2的调用是同步的:它等待函数2完成。你没有什么特别的事情要做。 –

+1

可能过早地暴露于AJAX,并且破坏了他们对编程的感知。 – TheZ

回答

0

在这里你去:

function1(i){ 
    //some code here 
    if(i == 1){ 
     function2(i); // call function2 and waits the return to continue 
    } 
    //the following code 
} 

function2(i){ 
    //do something here and returns 
} 

如果你意味着function2实际上是异步以某种方式:

function1(i){ 
    //some code here 
    if(i == 1){ 
     // call function2 and waits for return to continue 
     function2(i, function() { 
      // the following code 
     }); 
    } 
    else { 
     //the following code 
    } 
} 

function2(i, callback){ 
    //do something async here and return when complete 
    setTimeout(callback, 1000); 
} 
+0

嘻嘻,好笑!但是,我认为这个人在做异步并且不知道它?如果是这种情况,我可能会建议添加回调参数 – robnardo

+0

没有什么异步的代码...但我添加了一个异步示例以防万一。 – Bill

+0

完美的作品!唯一的问题是,我不想复制“下面的代码”,但我知道如何使这个失效。感谢您的支持! – dvd