[JavaScript/Node.JS] How to pass variables to asynchronous callbacks

[JavaScript/Node.JS] How to pass variables to asynchronous callbacks

A link to this has been in my bookmarks for ages, so it’s time to make a post to write this down.

var request = require('request');
var links = ['https://google.com', 'https://yahoo.com'];
for (link in links) {
    (function(url) {
        request(url, function() {
            console.log(url);
        });
    })(links[link]);
}

Notice the brackets around the function(url) and })(links[link]) then passes the link to that function.

Check out the [source]/source if my explanation doesn’t make sense. (Please let me know too)

Leave a Reply

Your email address will not be published. Required fields are marked *