2012-10-06 113 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