Discord.js is not expecting the return of the function

Asked

Viewed 118 times

-1

I am developing a BOT where I need to make a request (GET) for an API that returns me a JSON. This part is apparently working properly, I put this request in a separate file and created a function to call in my main function.

The problem is that when I call the function, before receiving its return my program already returns undefined and a few seconds after the function finishes processing the request.

How do I force my Main to wait for the return of the function?

I even tried to use async and await but I’m very lay in Javascript and I don’t know if it’s correct.

File apiCall.js

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 = {
        
    async 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 apiString = JSON.stringify(body);
                    var fechamento = api['Time Series (Daily)']['2020-10-06']['4. close'];
                    console.log("API fechamento: ", fechamento);
                    var now = new Date();

                    var tempo = now.getMilliseconds() - time.getMilliseconds();
                    console.log(`tempo para a API fazer o request: ${tempo}`);
                    return fechamento;
                });

            }).on('error', function (e) {
                console.log("Got an error: ", e);
            });
        
        }catch(err){
            console.log(err)
    }
}
};

File LMF.js

const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require('./config.json');
const api = require('./apiCall.js');



bot.login(config.token);

bot.on('message', async message => {
    if(message.author.bot) return;
   
    const CompleteMessage = message.content.toUpperCase();
    if(CompleteMessage.indexOf(config.prefix) !== 0) return;

    let args = message.content.toLowerCase().split(" ");
    switch (args[1]) {

             
        case 'teste':
                
                
                api.apiGet(args[2])
                .then(fechamento =>{
                     message.channel.send(fechamento);
                }).catch(err=>{
                    console.log(err);
                });                

                
                
                
                
                
                
            break; 

        default:
            message.channel.send("Para acessar a lista de comandos digite !LMF help");
            break;
        
    }
});

1 answer

0

I was able to solve the problem by changing http request to a synchronous method using the Sync-request package instead of the standard Javascript package I was using.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.