Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用node.js的递归模式循环大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
香港专业教育学院一直试图使用Node.js迭代一系列城市,并发出迭代请求谷歌的方向每个(我然后 JSON.parse抽象驱动时间).我需要找到一种同步执行此操作的方法,否则我将立即从每个城市的谷歌请求所有信息.我在 http://tech.richardrodger.com/2011/04/21/node-js-%E2%80%93-how-to-write-a-for-loop-with-callbacks/找到了一个很好的模式但是无法让回调起作用.如您所见,我使用’show’函数来测试它.我的代码如下:

var @R_772_10613@est = @R_772_10613@ire('@R_772_10613@est');
var fs = @R_772_10613@ire('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){
 @R_772_10613@est('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)

我遇到的问题是只输出数组中的第一个城市,并且回调/迭代永远不会继续.有什么想法,我出错了吗?

解决方法@H_197_13@
我也遇到过这样的问题,所以我编写了一个递归回调函数,它将作为for循环,但你可以控制何时递增.以下是该模块,名称为syncFor.js并将其包含在您的程序中

@H_374_7@module.exports = function syncFor(index,len,status,funC) { func(index,function (res) { if (res == "next") { index++; if (index < len) { syncFor(index,"r",func); } else { return func(index,"done",function () { }) } } }); } //this will be your program if u include this module var @R_772_10613@est = @R_772_10613@ire('@R_772_10613@est'); var fs = @R_772_10613@ire('fs'); var arr = ['glasgow','doncaster']; var syncFor = @R_772_10613@ire('./syncFor'); //syncFor.js is stored in same directory //the following is how u implement it syncFor(0,arr.length,"start",function (i,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,callBACk) { @R_772_10613@est('https://maps.googleapis.com/maps/api/directions/json?origin=' + a + '&desTination=' + b + '&region=en&sensor=false',function (err,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); }); };

大佬总结

以上是大佬教程为你收集整理的使用node.js的递归模式循环全部内容,希望文章能够帮你解决使用node.js的递归模式循环所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。