Home > Software engineering >  Code runs before request is completed on NodeJS
Code runs before request is completed on NodeJS

Time:10-21

I have the following code: (the code runs without issues)

function getValoresAcao(acoes) {
  acoes.forEach(acao => {
    getValorAcao(acao)
  }); 
  console.log("the end")
}

function getValorAcao(acao) {
  url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&parse_mode=HTML&symbol=' acao '&apikey=' API_KEY
  request(url, { json: true }, (err, res, body) => {
    if (err) { return console.log(err); }

    let contador = 0;
    let valorDeDoisDias = [];

    const dailyJsonObject = body["Time Series (Daily)"]
    var objectKeysArray = Object.keys(dailyJsonObject)
    objectKeysArray.forEach(function(objKey) {
        var objValue = dailyJsonObject[objKey]
        if (contador < NUMERO_DE_ELEMENTOS ) 
        {
          //console.log(dailyJsonObject);
          const valorFechamento = objValue["4. close"]
          console.log(valorFechamento);
          contador = contador   1
          valorDeDoisDias.push(valorFechamento);
      
        }
    });

    const textoDiferenca = getDiferencaEmPorcentagem(valorDeDoisDias);

    let bigString = ""   acao   " | "   valorDeDoisDias[0]   " | "   textoDiferenca
    request(urlTelegram   bigString, { json: true }, (err, res, bodyTelegram) => {
      console.log(bodyTelegram);
    })


  });
}



function getDiferencaEmPorcentagem(valprDeDoisDias) {
  let myString = ""
  const valorDiaAnterior = valprDeDoisDias[0]
  const valorDiaMaisRecente = valprDeDoisDias[1]
  myString = (valorDiaAnterior - valorDiaMaisRecente ) / valorDiaMaisRecente * 100
  myString = myString.toFixed(2)
  console.log(myString)
  return myString   "%"
}

But the code console.log("the end") is supposed to run after the request is completed, but it runs when I start the code, it didn't wait the request to be finished.

How can I make the "the end" part of the code wait the request be executed?

CodePudding user response:

probably something like that could help:

    async function getValoresAcao(acoes) {
        await Promise.all(acoes.map(getValorAcao))
        console.log("the end")
    }

    async function getValorAcao(acao) {
        const url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&parse_mode=HTML&symbol='   acao   '&apikey='   API_KEY
        return new Promise ((resolve, reject)=>{
            try{
                request(url, { json: true }, (err, res, body) => {
                    if (err) { 
                        throw err
                    }
            
                    let contador = 0;
                    let valorDeDoisDias = [];
            
                    const dailyJsonObject = body["Time Series (Daily)"]
                    var objectKeysArray = Object.keys(dailyJsonObject)
                    objectKeysArray.forEach(function (objKey) {
                        var objValue = dailyJsonObject[objKey]
                        if (contador < NUMERO_DE_ELEMENTOS) {
                            //console.log(dailyJsonObject);
                            const valorFechamento = objValue["4. close"]
                            console.log(valorFechamento);
                            contador = contador   1
                            valorDeDoisDias.push(valorFechamento);
            
                        }
                    });
            
                    const textoDiferenca = getDiferencaEmPorcentagem(valorDeDoisDias);
            
                    let bigString = ""   acao   " | "   valorDeDoisDias[0]   " | "   textoDiferenca
                    request(urlTelegram   bigString, { json: true }, (err, res, bodyTelegram) => {
                        if(err){
                            throw err
                        }
                        resolve(bodyTelegram)
                    })
                });
            } catch (e) {
                reject(e)
            }
        })
    }

    function getDiferencaEmPorcentagem(valprDeDoisDias) {
        let myString = ""
        const valorDiaAnterior = valprDeDoisDias[0]
        const valorDiaMaisRecente = valprDeDoisDias[1]
        myString = (valorDiaAnterior - valorDiaMaisRecente) / valorDiaMaisRecente * 100
        myString = myString.toFixed(2)
        console.log(myString)
        return myString   "%"
    }
  • Related