簡體   English   中英

module.exports 未在 Node.js 中返回結果

[英]module.exports not returning result in Node.js

我在 latestVideo.js 文件中有這個 function:

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;

然后在另一個文件中,我想使用 function 的 output ,例如:

const latestVideo = require('./latestVideo');

console.log(latestVideo.getLatestVideo)

但它不執行 function。 它只是在我的控制台中顯示[Function: getLatestVideo] 但是我返回了一個正確的值,那么為什么 function 沒有執行呢?

像這樣嘗試: latestVideo.getLatestVideo()

你得到未定義,因為你沒有返回任何東西。 您在回調 function 中使用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);
         }
     });
   })
}

您沒有運行 function 只是返回 function

制作latestVideo.getLatestVideolatestVideo.getLatestVideo()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM