Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/43.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript module.exports未在Node.js中返回结果_Javascript_Node.js - Fatal编程技术网

Javascript module.exports未在Node.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

我在最新的video.js文件中有此函数:

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,但是谢谢,非常有用的评论