JavaScript从函数返回值 [英] JavaScript return value from function

查看:108
本文介绍了JavaScript从函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们,以下的代码不能正常返回'baz'。它说它没有定义。为什么?

  getJSON = function(options,onResult)
{
//console.log(休息::的getJSON);
var prot = options.port == 8443? https:http;
var req = prot.request(options,function(res)
{
var output ='';
console.log(options.host +':'+ statusCode);
res.setEncoding('utf8');

res.on('data',function(chunk){
output + = chunk;
}};

res.on('end',function(){
var obj = JSON.parse(output);
onResult(res.statusCode,obj);
});
});
req.on('error',function(err){
//res.send('error:'+ err.message);
});
req.end();
};

exports.Search = function(req,res){
if(!req.session.username){
res.redirect('/ login');
} else {

options = {
host:'api.host.com',
port:443,
path:'/ ver / foo /'+ req.body.bar,
方法:'GET',
rejectUnauthorized:false,
requestCert:true,
代理:false,
标题: {
'Content-Type':'application / json'
}
};

var baz = getJSON(options,function(statusCode,result){
console.log(onResult:(+ statusCode +)+ JSON.stringify(result));
//检查用户是否存在
status = JSON.stringify(result.Count)
status = JSON.parse(status)
if(status == 0){
res.render('foo / bar',{title:'Title',Results:status,req:req});
} else {
results = JSON.stringify(result.Items)
results = JSON.parse(results)
name = results [0] .name.S
console.log(Found,name)
res.render('views / bar',{title:'title',results:results,req:req});
}
baz ='test';
return baz;
});
}
console.log(baz);
};


解决方案

您不能从异步成功处理程序返回结果就像你想要做的那样。操作是异步的。 getJSON函数返回后,它完成LONG。因此,getJSON函数返回时没有返回结果。



getJSON调用只是启动操作,然后getJSON调用完成执行,然后稍后,getJSON调用完成并执行回调。从回调函数返回值只是进入异步基础结构的大小便被忽略。它不会在你的代码中任何地方。



使用异步结果的唯一方法是使用成功处理程序中的值或从成功处理程序调用函数,通过这个函数,你刚刚收到的数据。



如果要使用异步网络通话,您必须以异步方式进行编程。这需要重写代码的流程,并且不能以典型的顺序方式编写代码。


Folks, following bit of code does not return 'baz' properly. It says its undefined. Why?

getJSON = function(options, onResult)
{
    //console.log("rest::getJSON");
    var prot = options.port == 8443 ? https : http;
    var req = prot.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });
    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });
    req.end();
};

exports.Search = function(req, res){
    if (!req.session.username) {
        res.redirect('/login');
    } else {

        options = {
            host: 'api.host.com',
            port: 443,
            path: '/ver/foo/'+req.body.bar,
            method: 'GET',
            rejectUnauthorized: false,
            requestCert: true,
            agent: false,
            headers: {
                'Content-Type': 'application/json'
                }
        };

        var baz = getJSON(options,function(statusCode, result) {
            console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
            // Check if User Exists
            status = JSON.stringify(result.Count)
            status = JSON.parse(status)
            if (status == 0) {
                res.render('foo/bar', { title: 'Title', Results: status, req: req });
            } else {
                results = JSON.stringify(result.Items)
                results = JSON.parse(results)
                name = results[0].name.S
                console.log("Found ",name)
                res.render('views/bar', { title: 'title', results: results, req: req });
            }
            baz = 'test';
            return baz;
        });
    }
 console.log(baz);
};

解决方案

You can't return results from an async success handler like you are trying to do. The operation is asynchronous. It finishes LONG after the getJSON function has returned. Thus, there is no result to return when the getJSON function returns.

The getJSON call just STARTS the operation, then the getJSON call finishes executing and then sometime later, the getJSON call completes and your callback is executed. Returning a value from the callback function just goes into the bowels of the async infrastructure and is ignored. It does not go to your code anywhere.

The ONLY way to use an asynchronous result is to use the value in the success handler or call a function from the success handler and pass that function the data that you just received.

If you're going to use asynchronous networking calls, you have to program in an asynchronous fashion. This requires reworking the flow of your code and you cannot write code in a typical sequential fashion.

这篇关于JavaScript从函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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