JavaScript从函数返回值

编程入门 行业动态 更新时间:2024-10-13 08:18:32
本文介绍了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', 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', 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从函数返回值

本文发布于:2023-11-26 02:27:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632283.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!