为什么模块导出variables是空的?

我是nodejs的新手。

这是我的.js文件。 我试图将audioDatavariables暴露给其他函数。 audioDatavariables的值在函数外部是空的。 当我在函数内部打印时,我看到了这个值。 什么可能是错的?

'use strict'; var asyncrequest = require('request'); var xml2js = require('xml2js'); var parseString = xml2js.parseString; var audioData = []; asyncrequest("http://example.com/feed", function(error, responsemeta, body) { parseString(body, function(err, result){ var stories = result['rss']['channel'][0]['item']; console.log("Total stories: " + stories.length); stories.forEach(function(entry) { var singleObj = {} singleObj['title'] = entry['title'][0]; singleObj['value'] = entry['enclosure'][0].$.url; audioData.push(singleObj); }); }); console.dir(audioData); }); module.exports = audioData; console.log("Program ended"); 

你将不得不为audio数据返回一个承诺,而不是audio数据本身! 你可以在别处学到更多的承诺。 令人高兴的是有一个promisified版本的请求,请求承诺,你可以这样使用:

 'use strict'; var rp = require('request-promise'); var xml2js = require('xml2js'); var parseString = xml2js.parseString; var audioData = []; var promiseForAudioData = rp('http://example.com/feed') .then(body => { parseString(body, function(err, result){ var stories = result['rss']['channel'][0]['item']; console.log("Total stories: " + stories.length); stories.forEach(function(entry) { var singleObj = {} singleObj['title'] = entry['title'][0]; singleObj['value'] = entry['enclosure'][0].$.url; audioData.push(singleObj); }); }); return audioData; }) .catch(console.error.bind(console)); module.exports = promiseForAudioData; console.log("Program ended"); 

如果您不想使用承诺,则可以在callback中导出或导出请求方法本身。

 asyncrequest("http://example.com/feed", function(error, responsemeta, body) { parseString(body, function(err, result){ var stories = result['rss']['channel'][0]['item']; console.log("Total stories: " + stories.length); stories.forEach(function(entry) { var singleObj = {} singleObj['title'] = entry['title'][0]; singleObj['value'] = entry['enclosure'][0].$.url; audioData.push(singleObj); }); module.exports = audioData; }); }); // Or exports.get = function (callback) { return asyncrequest(/* ... */, callback); } // Other module require("./module").get(function (audioData) { /* Do something */ }) 
Interesting Posts