2015-06-20 144 views
0

我已經看到了循環內循環需要等待回調的回調示例,我不知道如何將這些回答應用到我的腳本中。在雙循環中回調

其實我有一個雙循環,這樣的:

var marker = [{43.000,-79.321},...]; 
var result = []; 

function test(){ 
    for(var i=0; i<marker.length;i++){ 
     result[i] =[]; 
     for(var j=0; j<marker.length;j++){ 
      drivingDistance(marker[i],marker[j],i,j,function(cb){ 
       result[cb.i][cb.j] = cb.distance; 
      }); 
     } 
    } 
} 

function drivingDistance(Point1,Point2,i,j,cb){ 
    cb({distance:'something',i:i,j:j}); 
} 

誰能幫助?

回答

0

作爲本地遞歸替代方法,這裏有一個方法去做

var marker = [[43.000,-79.321],[44.000,-79],[45.000,-78],[46.000,-77]]; 
var result = []; 
var i=0, j=0; 

function test(){ 
    if(j >= marker.length){ j=0; i++; } // j is done one lap, reset to 0, i++ for next lap 
    if(i >= marker.length){ return false; } // if there are no more laps, stop recursion 
    if(j == 0){ result[i] = []; } // new lap, set result[i] as empty 

    drivingDistance(marker[i],marker[j],i,j,function(cb){ 
     result[cb.i][cb.j] = cb.distance; 
     j++; // increment j before next recursion 
     test(); 
    }); 
} 

function drivingDistance(Point1,Point2,i,j,cb){ 
    cb({distance:'something',i:i,j:j}); 
} 

test(); 
0

首先,你應該用方括號[]握住你的點,而不是curly那些

var marker = [[43.000,-79.321]]; // instead of [{43.000,-79.321}] 
      ^   ^

然後,你只需要使用遞延/承諾概念,你的所有內部回調同步如下

var marker = [[43.000,-79.321]]; 
var result = []; 

function test(){ 
    var deferreds = []; 

    for(var i=0; i<marker.length;i++){ 
     result[i] =[]; 
     for(var j=0; j<marker.length;j++){ 

      // add all your deferred instances returned by drivingDistance 
      deferreds.push(drivingDistance(marker[i],marker[j],i,j)); 
     } 
    } 

    $.when.apply(null, deferreds).then(function() { 
    var cbs = arguments, 
     cb 
    ; 

    for(var j = 0 ; j < cbs.length ; j++) { 
     cb = cbs[j]; 
     result[cb.i][cb.j] = cb.distance; 
    } 

    }).done(function() { 

     // You can safely print out the result array 
     console.log(result); 
    }); 

} 

function drivingDistance(Point1,Point2,i,j,cb){ 

    var d = $.Deferred(); 

    d.resolve({distance:'something',i:i,j:j}); 

    return d; 
} 

test(); 

jQuery.When以獲取更多信息

+0

你應該在你的答案中指出代碼錯誤太:) - 你[編輯問題](http://stackoverflow.com/review/suggested-編輯/ 8519581)來解決 – James

+0

謝謝@詹姆斯的幫助:) – mshaaban