2013-04-03 37 views

回答

1

node-sync模塊可以幫助您做到這一點。但請小心,這不是node.js的方式。

0

雖然我不會推薦它,但使用某種忙碌的等待可以輕鬆完成。例如:

var flag = false; 
asyncFunction(function() { //This is a callback 
    flag = true; 
}) 

while (!flag) {} 

while循環將持續循環,直到執行回調,從而阻止執行。你可以想象這會讓你的代碼非常混亂,所以如果你打算這麼做(我不推薦),你應該使用某種幫助函數來包裝你的異步函數;類似於Underscore.js的功能函數,如throttle。您可以通過查看annotated source來查看它們的工作原理。

2

要在「多線程環境」中將異步函數變爲同步,我們需要設置一個循環來檢查結果,從而導致阻塞。

下面是JS示例代碼:

function somethingSync(args){ 
    var ret; //the result-holding variable 
    //doing something async here... 
    somethingAsync(args,function(result){ 
    ret = result; 
    }); 
    while(ret === undefined){} //wait for the result until it's available,cause the blocking 
return ret; 
    } 

OR

synchronize.js也有幫助。