使用recursion模式循环与node.js

一直试图使用node.js迭代通过城市数组,并对每个方向(我然后JSON.parse抽象驱动器时间)作出一个迭代的请求谷歌的方向。 我需要find一种方法来做到这一点,否则我只是要求一次从每个城市谷歌的所有信息。 我在http://tech.richardrodger.com/2011/04/21/node-js-%E2%80%93-how-to-write-a-for-loop-with-callbacks上find了一个很好的模式/但不能得到callback工作。 正如你所看到的,即时通讯使用“显示”function来testing相同的。 我的代码如下:

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) 

我遇到的问题是只输出数组中的第一个城市,并且callback/迭代不会继续。 任何想法,我会出错请吗?

我也面临这样的问题,所以我写了一个recursioncallback函数,它将作为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); }); }; 

感谢指针,显然是由于我对JavaScript的callback不甚了解。 只是读O'Reilly的JavaScript模式,并点击“callback模式”部分 – 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)