等待请求完成Node.js [英] Wait for request to finish Node.js

查看:92
本文介绍了等待请求完成Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在确定如何在返回任何数据之前等待请求完成时遇到问题。我不相信我可以用回调做到这一点,我无法找到一个使用EventEmitter来做到这一点的好方法。我无法使用回调的原因是因为我的流程目前是这样的。

I am currently having an issue with figuring out how to wait for the request to finish before returning any data. I do not believe I can do this with a Callback and I have not been able to figure out a good way of using the EventEmitter to do it. The reason I cannot use a callback is because my flow currently works like this.


请求进入服务器>生成XML>联系远程API,获取
详细信息以完成生成XML>完成生成XML>返回
请求客户

Request comes into server > Generate XML > Contact remote API for details to finish generating XML > Finish Generating XML > Return request to client

我目前的代码与下面的代码非常相似。

The code I currently have looks very similar to the code included below.

Web服务器:

var xml = require('./XMLGenerator');
response.writeHead(200, {'Content-Type': 'text/xml'});
response.write(xml.generateXML());
response.end();

XML生成器:

function generateXML(){
// Code to generate XML
var API = require('./API');
var response = API.getItems("5");
for(var i = 1; i <= response.length; i++)
{
  // more code to generate further XML using the API response
}

// Finish generating and return the XML
}

API Grabber:

API Grabber:

function getItems(sort_by, amount) {
var request = require("request")

var url = "https://url.com/api/get_items.json?amount=" + amount;
request({
    url: url,
    json: true
}, function (error, response, body) {
    console.log('we got here!');
   if (!error && response.statusCode === 200) {
        var items = body.data.items;
        console.log(items);

        return items;
    } else {
        console.log("Error connecting to the API: " + url);
        return;
    }
})
}

运行代码并直接测试时返回undefined含义该请求尚未提出。我只需要知道一种方法,让XML生成器在继续生成之前等待请求完成。 (我输入的psudeo代码中可能存在轻微错误,因为它不是来自源的精确复制粘贴,但它确实可以在此流程中工作)

When running the code and testing directly it returns "undefined" meaning that the request has not been made yet. I just need to know a way to make the XML generator wait for the request to finish before continuing on with the generation. (there may be minor errors in the psudeo code I typed up as it is not an exact copy paste from the source, it does however work in this flow)

我是只是使用不好的做法,或者这是我应该尝试这个的正确方法吗?

Am I just using bad practices, or is this the correct way that I should be attempting this?

编辑:问题是没有加载模块/ API文件,加载完全没问题。问题是请求大约需要2秒钟才能完成,并且该节点在请求完成之前继续运行。

The problem is not loading the module/API file, that loads perfectly fine. The problem is that the request takes about 2 seconds to complete, and that node moves on before the request completes.

推荐答案

您需要使用回调。将您的API抓取器更改为:

You need to use callbacks. Change your API grabber to this:

function getItems(amount, callback) {
// some code... 
request({
  url: url,
  json: true
}, function (error, response, body) {
   // some code...
   if (!error && response.statusCode === 200) {
      // some code    
      callback(items); <-- pass items to the callback to "return" it
   }
})
}

然后更改xml生成器也接受回调:

Then change the xml generator to also accept callbacks:

function generateXML(callback){
// Code to generate XML
var API = require('./API');
API.getItems("5",function(response){
  for(var i = 1; i <= response.length; i++)
  {
    // more code to generate further XML using the API response
  }

  // Finish generating and return the XML
  callback(xml_result); // <-- again, "return" the result via callback
});
}

然后在您的服务器代码中执行:

Then in your server code do:

var xml = require('./XMLGenerator');
response.writeHead(200, {'Content-Type': 'text/xml'});
xml.generateXML(function(xmlstring){
    response.write(xmlstring);
    response.end();
});

这篇关于等待请求完成Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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