NodeJS 获取异步返回值(回调) [英] NodeJS get async return value (callback)

查看:130
本文介绍了NodeJS 获取异步返回值(回调)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上阅读了有关回调的信息,但就我而言,我无法理解它们.

I have read around the internet about callbacks but I just can't understand them in my case.

我有这个功能,它在运行时记录到控制台.但是,我现在需要在另一个函数中进行此响应,而我正在努力做到这一点.

I have this function, and it logs to console when it runs. However I now need this response in another function and I am struggling to do so.

var asyncJobInfo = function(jobID, next) {

    var oozie = oozieNode.createClient({ config: config });

    var command = 'job/' + jobID + '?show=info';

    console.log("running oozie command: " + command);

    oozie.get(command, function(error, response) {

    console.log("*****response would dump to console here:*****");
//  console.log(response);
    return response;
    });
};

这是我应该得到它的地方:(这显然不起作用,因为它不等待响应.)

This is where I should get it: (This obviously doesn't work because it doesn't wait for the response.)

exports.getJobInfoByID = function(req, res) {

    var jobIDParam = req.params.id;
    res.send(asyncJobInfo(jobIDParam));
}

我真的很难理解回调,而且我在这里目瞪口呆.

I really struggle to wrap my head around callbacks and I'm staring myself blind here.

推荐答案

回调无法返回值,因为它们将返回的代码已经执行.

Callbacks can't return a value as the code they would be returning to has already executed.

所以你可以做一些事情.一个传递回调函数,一旦你的异步函数获取数据调用回调并传递数据.或者传递响应对象并在你的异步函数中使用它

So you can do a couple things. One pass a callback function and once your async function gets the data call the callback and pass the data. Or pass the response object and use it in your async function

传递回调

exports.getJobInfoByID = function(req, res) {
    var jobIDParam = req.params.id;
    asyncJobInfo(jobIDParam,null,function(data){
       res.send(data);
    });
}

var asyncJobInfo = function(jobID, next,callback) {
    //...
    oozie.get(command, function(error, response) {
       //do error check if ok do callback
       callback(response);
    });
};

传递响应对象

exports.getJobInfoByID = function(req, res) {
    var jobIDParam = req.params.id;
    asyncJobInfo(jobIDParam,null,res);
}

var asyncJobInfo = function(jobID, next,res) {
    //...
    oozie.get(command, function(error, response) {
       //do error check if ok do send response
       res.send(response);
    });
};

这篇关于NodeJS 获取异步返回值(回调)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆