node.js - 我可以让我的 NodeJS 服务器等待函数调用吗?我的程序完成得太快了
问题描述
粘贴在下面的代码中的以下代码调用速度太快了:
global.h2=jsonifiedver(l.number)
太慢了。我怎样才能让它等待从 jsonifiedver() 函数调用得到答案,这样我才能得到正确的答案。我尝试使用全局变量,这些工作,但只有在每第二次调用之后,加上这就是我知道调用工作的方式,只是程序结束得太快,然后在第二次调用时它有我想要的数据。我是 nodejs 的新手,因此不胜感激。谢谢!
const server = http.createServer((req, res) => {
if (req.method == 'POST') {
var body = ''
req.on('data', function(data) {
body += data
global.l = JSON.parse(body)
l = JSON.parse(body)
global.h2=jsonifiedver(l.number) // This call is slow and doesnt
// finish in time
global.h3 = JSON.stringify(h2)
console.log('Partial body: ' + body, global.l, global.l.number)
console.log("POST")
res.end("Not The real end");
})
} else {
console.log("GET")
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json'); // 'text/plain');
console.log(global.l)
res.end(global.h3); //"End");
});
所以 res.end(global.h3) 在我对 global.h2=jsonifiedver(l.number) 的函数调用完成之前完成。所以我没有得到我需要的答案。那有意义吗?
解决方案
您遇到的问题是,当调用请求时,req.on('data', function(){})
只是为data
事件添加了一个钩子,但您还使用res.end()
afterelse
语句返回了响应。除非触发,否则不应发回响应req.on('end')
,这意味着请求数据已结束。在data
事件中,理想情况下,您应该只将数据附加到body
,然后在end
事件处理程序上,您应该处理正文并返回响应。如下:
const server = http.createServer((req, res) => {
const methodType = req.method;
if (methodType === "GET") {
console.log("GET");
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
console.log(global.l);
res.end(global.h3);
} else if (methodType === 'POST') {
console.log("POST")
var body = ''
req.on('data', function(data) {
body += chunk;
});
req.on('end', function() {
global.l = JSON.parse(body);
l = JSON.parse(body);
global.h2=jsonifiedver(l.number);
global.h3 = JSON.stringify(h2);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
console.log(global.l);
res.end(global.h3);
});
}
});
如果您正在等待jsonifiedver()
调用完成,请确保将其定义为Promise
/Async
函数,然后您可以使用 调用它await
,确保您调用的包装函数也jsonifiedver()
已定义async
。
推荐阅读
- python - 如何从多个游标分隔的字典(dictfetchall)中获取值?
- apache-kafka - KSQL 事件合并 - 基于时间戳组合来自单个流的事件
- javascript - Javascript 排序适用于 Firefox 而不是 Chrome
- php - php android推送通知设置高优先级
- android - Gradle 依赖冲突解决:
- graphql - 对于 GraphQL 中的可空字段,是否可以省略返回字段而不是 null?
- python - 将时间添加到日期时间字段
- c# - 如果达到某个条件,如何使构造函数产生 null?
- python - 更改销售时生成幻灯片动画左翼
- python - Chromedriver 在抓取时不断更改时区