2012-04-15 4 views
7

ive node.jsを使用して都市の配列を反復し、それぞれの方向についてgoogleに反復的にリクエストしています(次にドライブ時間を抽象化するJSON.parse)。私はこれを同期的に行う方法を見つけ出す必要があります。そうでなければ、私はただちに各都市のgoogleからすべての情報を要求します。私はhttp://tech.richardrodger.com/2011/04/21/node-js-%E2%80%93-how-to-write-a-for-loop-with-callbacks/で使用するのに良いパターンを見つけましたが、コールバックを動作させることはできません。あなたが見ることができるように、私は同じものをテストするために 'ショー'機能を使用しています。私のコードは次の通りです:node.jsで再帰パターンループを使用する

var request = require('request'); 
var fs = require('fs'); 
var arr = ['glasgow','preston','blackpool','chorley','newcastle','bolton','paris','york','doncaster']; 
//the function I want to call on each city from [arr] 
function getTravelTime(a, b,callback){ 
request('https://maps.googleapis.com/maps/api/directions/json?origin='+a+'&destination='+b+'&region=en&sensor=false',function(err,res,data){ 
var foo = JSON.parse(data); 
var duration = foo.routes[0].legs[0].duration.text; 
console.log(duration); 
}); 
}; 

function show(b){ 
fs.writeFile('testing.txt',b); 
}; 


function uploader(i){ 
if(i < arr.length){ 
    show(arr[i],function(){ 
    uploader(i+1); 
    }); 
} 
} 
uploader(0) 

問題は、配列の最初の都市だけが出力され、コールバック/反復が進まないことです。どのようなアイデアがうまくいかないのですか?

+2

プログラム、だらしのための謝罪、私は質問を投稿した最初の時間でこれを含めます。 –

+0

あなたの例にはいくつかの間違いがあります: 'fs.writeFile'のパラメータの数が間違っています。関数' show'は1つのパラメータをとりますが、2で呼び出します。 – mihai

+0

show()関数はコールバックこの例では再帰はありません。 –

答えて

11

私はまた、このような問題に直面していたので、私は用として機能する再帰的コールバック関数を書いている:これは、コードが動作する方法を知っていない人のために

、ループすることはできますが、増分するタイミングは制御できます。以下はsyncFor.jsとしてそのモジュール、名前で、私は今それを少し整理している

module.exports = function syncFor(index, len, status, func) { 
    func(index, status, function (res) { 
     if (res == "next") { 
      index++; 
      if (index < len) { 
       syncFor(index, len, "r", func); 
      } else { 
       return func(index, "done", function() { 
       }) 
      } 
     } 
    }); 
} 

//this will be your program if u include this module 
var request = require('request'); 
var fs = require('fs'); 
var arr = ['glasgow', 'preston', 'blackpool', 'chorley', 'newcastle', 'bolton', 'paris', 'york', 'doncaster']; 
var syncFor = require('./syncFor'); //syncFor.js is stored in same directory 
//the following is how u implement it 

syncFor(0, arr.length, "start", function (i, status, call) { 
    if (status === "done") 
     console.log("array iteration is done") 
    else 
     getTravelTime(arr[i], "whatever", function() { 
      call('next') // this acts as increment (i++) 
     }) 
}) 


function getTravelTime(a, b, callback) { 
    request('https://maps.googleapis.com/maps/api/directions/json?origin=' + a + '&destination=' + b + '&region=en&sensor=false', function (err, res, data) { 
     var foo = JSON.parse(data); 
     var duration = foo.routes[0].legs[0].duration.text; 
     callback(); // call the callback when u get answer 
     console.log(duration); 
    }); 
}; 
+0

gitプロジェクトを作成した後、このリンクにアクセスしてくださいhttps://github.com/subramanya2107/SyncFor – subbu

14

ポインタのおかげで、明確にJavaScriptのコールバックの私の貧弱な理解の下にあった。 O'ReillyによるJavaScriptパターンの読み込みと 'Callback pattern'セクションの読み込み - doh!

var arr = ['glasgow','preston','blackpool','chorley','newcastle','bolton','paris','york','doncaster']; 

function show(a,callback){ 
    console.log(a); 
    callback(); 
} 

function uploader(i){ 
    if(i < arr.length){ 
    show(arr[i], 
     function(){ 
      uploader(i+1) 
     }); 
    }; 
} 
uploader(0) 
関連する問題