首页 > 解决方案 > 我可以让我的 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) 的函数调用完成之前完成。所以我没有得到我需要的答案。那有意义吗?

标签: node.jsasync-await

解决方案


您遇到的问题是,当调用请求时,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


推荐阅读