Wait for request to finish Node.js

后端 未结 2 689
既然无缘
既然无缘 2021-01-02 11:41

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 n

相关标签:
2条回答
  • 2021-01-02 12:06

    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
       }
    })
    }
    

    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();
    });
    
    0 讨论(0)
  • 2021-01-02 12:09

    Do these changes since request is async, use callbacks.

    API.getItems("5", function(rs){
          var response = rs;
          for(var i = 1; i <= response.length; i++)
          {
          // more code to generate further XML using the API response
          }
    
          // Finish generating and return the XML
        }
    
    });
    
    
    ...
    function getItems(sort_by, amount, callback) {...
    
    ...
    callback(items); //Instead of return items;
    
    ...
    

    You cannot return from an async call, which is request module in your case. In such cases you can either use promises or callbacks. This is a solution with callback.

    The actual problem of it returning undefined is it doesnot wait for var response = API.getItems("5"); to execute completely and executes the next line and hence you get response as undefined. I hope you get the point.\

    Also I hope

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

    is somewhere inside some callback of an API or http.createServer.

    0 讨论(0)
提交回复
热议问题