inetbug
inetbug

Reputation: 409

Variable in node.js JavaScript doesn't change

'use strict';

var http = require('http');

function simpleTest() {
    var content = '';
    http.get("http://google.com/", function (res) {
        var html = '';
        res.on('data', function (chunk) {
            html += chunk;
        });
        res.on('end', function () {
            content = html;
        });
    });
    return content;
}

console.log(simpleTest());

Why variable doesn't change and I get an empty string?

I think that the first function displays variable, and only then execute the http.get. How to make the first code executed and only then the function returns a variable?

Upvotes: 1

Views: 1018

Answers (1)

cookie monster
cookie monster

Reputation: 10972

It's because the operation is asynchronous. This means that simpleTest returns long before the http.get() response arrives.

Any code that needs the response must be invoked from in the callback. In your case, there could be multiple invocations of the data callback, so you need to handle it inside the end callback.

'use strict';

var http = require('http');

function simpleTest() {
    http.get("http://google.com/", function (res) {
        var html = '';
        res.on('data', function (chunk) {
            html += chunk;
        });
        res.on('end', function () {
            console.log(html);
        });
     });
}

simpleTest();

If you don't want to hardcode the console.log(), you can put it in a function, and pass the function to simpleTest(). This makes it much more generic.

'use strict';

var http = require('http');

function simpleTest(fn) {
    http.get("http://google.com/", function (res) {
        var html = '';
        res.on('data', function (chunk) {
            html += chunk;
        });
        res.on('end', function () {
            fn(html);
        });
     });
}

simpleTest(function(data) {
    console.log(data);
});

So here we passed a function to the fn parameter, and invoked the fn parameter inside the end callback.

When we invoke it, we pass the final html value, and the callback receives it in its data parameter.

These are very common patterns, so it would be a good idea to get familiar with them.

Upvotes: 2

Related Questions