Javascript module.exports未在Node.js中返回结果
我在最新的video.js文件中有此函数:Javascript module.exports未在Node.js中返回结果,javascript,node.js,Javascript,Node.js,我在最新的video.js文件中有此函数: function getLatestVideo() { request(url, function (error, response, body) { if (!error && response.statusCode === 200) { let reqBody = body.toString(); reqBody = JSON.parse(reqBody); const latest
function getLatestVideo() {
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
let reqBody = body.toString();
reqBody = JSON.parse(reqBody);
const latestVideoID = reqBody.items['0'].id.videoId;
return videoLink + latestVideoID;
}
});
}
module.exports.getLatestVideo = getLatestVideo;
然后在另一个文件中,我想使用函数的输出,如:
const latestVideo = require('./latestVideo');
console.log(latestVideo.getLatestVideo)
但它不执行该函数。它只是在我的控制台中显示
[函数:getLatestVideo]
。但是我正确地返回了一个值,那么为什么函数没有执行呢?像这样尝试:latestVideo.getLatestVideo()
你没有定义,因为你没有返回任何东西。在回调函数中使用return
。以下是您的问题的解决方案:
async function getLatestVideo() {
return await new Promise((resolve) => {
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
let reqBody = body.toString();
reqBody = JSON.parse(reqBody);
const latestVideoID = reqBody.items['0'].id.videoId;
resolve(videoLink + latestVideoID);
}
});
})
}
您没有运行函数,只是返回函数 制作
latestVideo.getLatestVideo
至latestVideo.getLatestVideo()
您需要只导出一个或多个函数吗?顺便说一句,我得到的结果不一样,我得到的是
未定义的
然后确定它可以工作。下一步是修复你的函数,因为它有一些问题我得到未定义
然后它工作了你的函数返回未定义
函数很可能有问题你在getLatestVideo()
函数中没有返回任何东西,而且你正在以未记录的方式使用请求
,了解回调是什么,并根据请求
函数获得结果。我正在学习Node.js,但是谢谢,非常有用的评论