如何解决HTTPS请求功能无需返回未定义
我真的是JavaScript的新手,正在从事一个项目,并且一直在尝试发出HTTPs请求。 当我直接执行此HTTP请求时,它可以工作,但是当我将其作为函数调用时,返回未定义,函数内部的console.log可以正常工作,但不返回。为什么呢?
const config = require('./config.json');
function formatDate(date) {
var d = new Date(date),month = '' + (d.getMonth() + 1),day = '' + d.getDate(),year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year,month,day].join('-');
}
module.exports = {
apiGet(symbol){
try{
var http = require('https');
var date = new Date();
if(date.getDay == 6 ){
date.setDate(date.getDate()-1);// se for Sabado pegar os dados de Sexta
} else if(date.getDay == 0){
date.setDate(date.getDate()-2);// se for Domingo pegar os dados de Sexta
}else if(date.getHours > '18'){
console.log('Horario OK');// pegando os dados de hoje pois a bolsa já fechou
} else {
date.setDate(date.getDate()-1);//Pegando os dados de ontem pois a bolsa ainda não fechou
}
var time = new Date();
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol='+symbol+'&apikey='+config.key;
http.get(url,function (res) {
var body = '';
res.on('data',function (chunk) {
body += chunk;
});
res.on('end',function () {
var api = JSON.parse(body);
var fechamento = api['Time Series (Daily)'][formatDate(date)]['4. close'];
console.log("API fechamento: ",fechamento);
return fechamento;
});
}).on('error',function (e) {
console.log("Got an error: ",e);
});
}catch(err){
console.log(err)
}
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。