【问题标题】:Wait for callback function to return in Node.js等待回调函数在 Node.js 中返回
【发布时间】:2013-12-31 19:20:56
【问题描述】:

我能够生成 Python child_process 并将 Python 返回的数据写入 Node.js 中的控制台。但是,我无法在 Node.js 的回调函数中返回数据。我在想这是因为回调函数是异步的,所以服务器在回调返回之前将结果返回给浏览器。

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

当我运行:node test_server.js,然后在浏览器中点击它,我在控制台中得到以下信息:

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

但我在浏览器中只有以下内容:

Testing 

谁能解释我如何等待回调函数返回后再继续?

谢谢。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    您需要将回调与 child_process 中的 close 事件挂钩。

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

    【讨论】:

    • 感谢您的回复。当我添加以下代码并注释掉原始 callBack(resp) 时,我在浏览器中没有得到任何东西。 child.on('close', function() { callBack(resp); });你能解释一下如何触发 child.on('close') 吗?
    • res. 调用移动到您传递给run() 的函数中,否则它们会在回调完成之前被调用。
    • 就是这样,结合您之前的评论。非常感谢!
    猜你喜欢
    • 2013-07-24
    • 2021-06-03
    • 1970-01-01
    • 2019-07-25
    • 2019-08-03
    • 2019-08-23
    • 2016-10-16
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多