[英]module.exports not returning result in Node.js
I have this function in a latestVideo.js file:我在 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;
Then in another file I want to use the output of the function like:然后在另一个文件中,我想使用 function 的 output ,例如:
const latestVideo = require('./latestVideo');
console.log(latestVideo.getLatestVideo)
But it does not execute the function.但它不执行 function。 It just says
[Function: getLatestVideo]
in my console.它只是在我的控制台中显示
[Function: getLatestVideo]
。 But I return a value right, so why is the function not executing?但是我返回了一个正确的值,那么为什么 function 没有执行呢?
Try it like this: latestVideo.getLatestVideo()
像这样尝试:
latestVideo.getLatestVideo()
You get undefined because you doesnt return anything.你得到未定义,因为你没有返回任何东西。 You use
return
in an callback function.您在回调 function 中使用
return
。 Here is a solution for your problem:这是您的问题的解决方案:
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);
}
});
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.