8

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で使用するのに適したパターンを見つけました/しかし、コールバックを機能させることができません。ご覧のとおり、imは「show」関数を使用して同じものをテストしています。私のコードは次のとおりです。

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)

私が抱えている問題は、配列の最初の都市のみが出力され、コールバック/反復が続行されないことです。私がうまくいかないアイデアはありますか?  

4

2 に答える 2

17

ポインタをありがとう、javascriptのコールバックの私の貧弱な理解に明らかにダウンしました。O'ReillyによるJavaScriptパターンを読んで、「コールバックパターン」セクションを押すだけです。

知らない人のために、これはコードがどのように機能するかです:

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) 
于 2012-04-18T19:31:27.030 に答える
12

私もこのような問題に直面していたので、forループとして機能する再帰的なコールバック関数を作成しましたが、いつインクリメントするかを制御できます。以下はそのモジュールであり、名前を付け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);
    });
};
于 2012-12-11T12:29:29.040 に答える