2015-01-14 115 views
0

我認爲在這種情況下一個例子是更好的超過1000個字:如何異步執行JavaScript代碼段並等待結果?

function fib(num) { 
    if (num <= 1) 
     return 1; 

    return fib(num-1) + fib(num-2); 
} 

function asyncFib(num) { 
    if (num <= 1) 
     return 1; 

    var a = asyncCall(fib, [num-1]); 
    // don't wait for fib(n-1) 
    // and perform fib(n-2) in 'parallel' 
    var b = asyncCall(fib, [num-2]); 

    // wait the results for fib(n-1) and fib(n-2) and use them 
    return a + b; 
} 

斐波那契算法只是一個例子,我想學習如何在JavaScript中添加併發的「分治法」。我發現node.js和異步包可能是一個答案,但我不知道如何。

有人可以幫我嗎? 謝謝!

回答

0

您可以使用PromiseJs

這一個簡單的例子:

var Promise = require('promise'); 

function fib(num) { 
return new Promise(function(resolve,reject){ 
if (num <= 1) 
    resolve(1); 

resolve(fib(num-1) + fib(num-2)); 
}); 

} 

function asyncFib(num) { 
if (num <= 1) 
    return 1; 
var promiseAResolved = false; 
var promiseBResolved = false; 

var a = asyncCall(fib, [num-1]).then(function(result){ 
    promiseAResolved = true; 

    if(promiseAResolved === true && promiseBResolved === true){ 
    return a + b; 
    } 

}); 

var b = asyncCall(fib, [num-2]).then(function(result){ 
    promiseBResolved = true; 

    if(promiseAResolved === true && promiseBResolved === true){ 
    return a + b; 
    } 

}); 


return a + b; 
} 

的更多信息:https://github.com/then/promise 和Q.js:https://github.com/kriskowal/q