问题描述
大家好,我的 Node JS 函数有问题,我希望它返回 https 获取请求最终编辑的数据,我知道这个异步问题有很多解决方案,但我都尝试了,但仍然无法弄清楚我的代码有什么问题? 这是我的功能,无需任何其他解决方案编辑:
function getMovie(apiKey,gen) {
const baseUrl = "https://api.themoviedb.org/3/discover/movie?api_key=" + apiKey + "&language=en-US&include_adult=false&include_video=false&page=1&with_genres=" + gen;
https.get(baseUrl,function (responce) {
console.log(responce.statusCode);
var d = "";
responce.on("data",function (data) {
d += data;
});
responce.on("end",() => {
const finalData = [];
const moviesData = JSON.parse(d);
const result = moviesData.results;
const maxx = result.length;
const rand = Math.floor(Math.random() * maxx);
const title = result[rand].title;
const rDate = result[rand].release_date;
const overview = result[rand].overview;
const imageRoot = result[rand].poster_path;
const movieId = result[rand].id;
const movierating = result[rand].Vote_average;
// here will push those variables to finalData array
// then return it
return finalData;
});
}).on('error',(e) => {
console.error(e);
});
}
并希望在此 finalData 返回后:
const finalResult = getMovie(apiKey,genre);
它总是返回未定义,我该如何解决这个问题?请任何人帮我解决这个问题 提前致谢。
解决方法
我使用以下代码使用 Promise 解决了这个问题:
const rp = require('request-promise');
function getMovie(url) {
// returns a promise
return rp(url).then(body => {
// make the count be the resolved value of the promise
let responseJSON = JSON.parse(body);
return responseJSON.results.count;
});
}
getMovie(someURL).then(result => {
// use the result in here
console.log(`Got result = ${result}`);
}).catch(err => {
console.log('Got error from getMovie ',err);
});