Node.JS: How to pass variables to asynchronous callbacks? [duplicate]

Your url variable is not scoped to the for loop as JavaScript only supports global and function scoping. So you need to create a function scope for your request call to capture the url value in each iteration of the loop by using an immediate function:

var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
    (function(url) {
        require('request')(url, function() {
            console.log(url);
        });
    })(linkshttps://stackoverflow.com/questions/13221769/node-js-how-to-pass-variables-to-asynchronous-callbacks);
}

BTW, embedding a require in the middle of loop isn’t good practice. It should probably be re-written as:

var request = require('request');
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
    (function(url) {
        request(url, function() {
            console.log(url);
        });
    })(linkshttps://stackoverflow.com/questions/13221769/node-js-how-to-pass-variables-to-asynchronous-callbacks);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)