问题描述:

This question already has an answer here:

  • How do I return the response from an asynchronous call?

    17 answers

网友答案:

Your getData function is asynchronously calling request, then immediately returning the value of responseString, which will always be ''.

Think about the code:

module.exports= {
    test: getData()
};

What is happening here? You are

  1. Immediately executing your getData function, which:
    • executes request, and
    • returns ''
  2. Exporting your module with a single field test containing this result ('').

So you are essentially doing this:

module.exports = {
    test: ''
};

Which I assume is not your intention. You probably want something closer to this:

module.exports = {
    test: getData
};

Excluding the parens means you are returning the function itself rather than the result of calling the function.

As you are working asynchronously you likely want to include a callback argument or return a promise from your getData function in order to access the results of the request. Perhaps something like this:

Data.js:

function getData (cb) {
    request('URL', function (err, response, body) {

       ...

       responseString = JSON.stringify(responseJSONArray);
       cb(responseString);
    });
}

module.exports = {
    test: getData
};

and then using it like this:

Index.js

var data = require('../public/javascripts/Data');
router.get('/', function (req, res, next) {
    data.test(function (responseString) {
        res.render('index', { d: responseString });
    });
});
相关阅读:
Top