简体   繁体   中英

Dynamically generate url and page content from multiple JSON files using node.js

I was trying to generate multiple url/pages using node.js express. I have multiple (currently 10 but the number may change) urls stored in one JSON file and I have another 10 (bound to change) JSON files that contain the information for each url respectively.

Currently I am using request-json to get the JSON file from a local server. However, my codes only allow me to create the very last url and its content in the loop

client.get("url1", function(error, response, body){                
    for (var i=0; i<10; i++){
        var urlName = body.row[i];
        client.get("url2" + urlName, function(error, response, body) {
            app.get('/'+ urlName, function (req, res){ 
                res.send(body);     
            })
        })
    }
});

I think It's because there is a async call in for loop. You are saying use current value of i or urlName in a async function app.get .

And app.get will be called when client.get will finished.

So when it will be called your for loop will be finished so it will call with latest value of i/urlName which will be your last row i=10 . So it goes for that.

try this:-

var performCurrentOperation = function(i,body){
    var urlName = body.row[i];
    client.get("url2" + urlName, function(error, response, body) {
        app.get('/'+ urlName, function (req, res){ 
            res.send(body);     
        });
    });
}

client.get("url1", function(error, response, body){                
    for (var i=0; i<10; i++){
        performCurrentOperation(i,body);
    }
});

Basically here what I am doing I've bind a function with that value of i so it should perform operation on current value of i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM