RobertFrenette
RobertFrenette

Reputation: 627

Wait for callback function to return in Node.js

I'm able to spawn a Python child_process and write the data returned from Python to the console in Node. However, I'm not able to return the data in a callback function in Node. I’m thinking this is because the callback function is asynchronous, so the server returns the result to the browser before the callback returns.

test_server.js

var sys = require('sys');
var http = require('http');
var HOST = '127.0.0.1';
var PORT = 3000;

function run(callBack) {
    var spawn = require('child_process').spawn,
        child = spawn('python',['test_data.py']);
    var resp  = "Testing ";

    child.stdout.on('data', function(data) {
        console.log('Data: ' + data); // This prints "Data: 123" to the console
        resp += data; // This does not concat data ("123") to resp
    });

    callBack(resp) // This only returns "Testing "
}

http.createServer(function(req, res) {
    var result = '';

    run(function(data) {
        result += data;
    });

    res.writeHead(200, {'Context-Type': 'text/plain'});
    res.end(result);
}).listen(PORT, HOST);

sys.puts('HTTP Server listening on ' + HOST + ':' + PORT);

test_data.py

import sys

out = '123';
print out

When I run: node test_server.js, then hit it in a browser, I get the following in the console:

c:\>node test_server.js
HTTP Server listening on 127.0.0.1:3000
Data: 123

But I only the following in the browser:

Testing 

Could someone explain how I can wait for the callback function to return before continuing?

Thanks.

Upvotes: 0

Views: 937

Answers (1)

Stuart
Stuart

Reputation: 575

You need to hook your callback up to the close event from the child_process.

child.on('close', function() {
    callBack(resp);
}

Upvotes: 1

Related Questions