等待异步操作,然后使用NodeJ在Express中执行渲染 [英] Wait a async operation before execute render in express using NodeJs
问题描述
我最近开始使用NodeJ,并且正在尝试创建一个API,该API将从Web获得一些信息并将其编译并显示给用户.
我的问题是关注
router.get('/',函数(req,res,next){https.get(pageUrl,函数(res){res.on('data',function(responseBuffer){//重要信息;信息= responseBuffer;}}res.render('page',{Important:info});}
如何等待直到拥有"info"变量,然后再发送res.render.因为现在,如果我尝试等待,通常程序会结束并且不要等待结果.
谢谢.
假设您的 https.get
调用为您提供了带有'end'
事件的流.[1] ,您可以执行以下操作:
router.get('/',函数(req,res,next){https.get(pageUrl,函数(res){var info;res.on('data',function(responseBuffer){//重要信息;信息= responseBuffer;}res.on('end',function(){res.render('page',{Important:info});})}}
请注意,上面的代码将不起作用,因为您已使用 https.get
回调中的 res
参数将基本的 res
参数遮盖了.
此外,请注意,可能会多次发出'data'
事件(同样,假设使用标准流实现 [1] ),因此您应该累积结果在您的 info
变量中.
[1] 您能否发布有关代码的更多信息,例如 https
库的来源(它是标准的HTTPS库吗?).>
个人思想:我强烈建议使用请求模块,该模块可通过在NPM上使用npm install request
,用于对外部服务的HTTP(S)请求.它有一个简洁的界面,易于使用,可以为您处理很多情况(重定向是一个示例,JSON是一个示例,而 Content-Type
是另一个示例).
I'm starting to use NodeJs recently and I'm trying to create a API that will get some information from web compile it and show to the user.
My question is the follow
router.get('/', function (req, res, next) {
https.get(pageUrl, function (res) {
res.on('data', function (responseBuffer) {
//Important info;
info = responseBuffer;
}
}
res.render('page', { important: info});
}
How can I wait until I have the "info" var and then send the res.render. Because right now if I try to wait it usually the program ends and don't wait the result.
Thanks.
Assuming your https.get
call gives you a stream with an 'end'
event [1], you can do the following:
router.get('/', function (req, res, next) {
https.get(pageUrl, function (res) {
var info;
res.on('data', function (responseBuffer) {
//Important info;
info = responseBuffer;
}
res.on('end', function() {
res.render('page', { important: info});
})
}
}
Note that the above code will not work because you shadowed the base res
parameter with the res
parameter from the https.get
callback.
Also, note that the 'data'
event may be emitted several times (again, assuming a standard stream implementation[1]), so you should accumulate the results inside your info
variable.
[1] Could you please post more information about your code, such as where the https
library comes from (is it the standard HTTPS lib?).
Personal thought: I highly suggest using the request module, disponible on NPM via npm install request
, for HTTP(S) requests to external services. It's got a neat interface, is simple to use and handles a lot of situations for you (redirects are one example, JSON and Content-Type
another).
这篇关于等待异步操作,然后使用NodeJ在Express中执行渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!