0

I am already trying to assign a value for a variable by HTTP callback. But when I try to assign it, the value isn't assigned on the getCurrentRate scope.

At the end of the html get I need to return the data object to the function that called getCurrentRates.

function getCurrentRates(baseCoin) {
    let data
    const uri = 'https://api.exchangeratesapi.io/latest?base=' + baseCoin
    https.get(uri, (res) => {
        let chuncks
        res.on('data', (chunck) => {
            chuncks += chunck
        })
        res.on('end', => {
            data = chuncks
        })
    })
}
  • 3
    Can you provide more information? Where are you using ```data```? What is the expected scope? There isn't enough here to provide an answer. – Chris Aug 19 '20 at 20:31
  • Try replacing: chuncks += chunck with data += chunck, and on 'end' return data – domenikk Aug 19 '20 at 20:34
  • I am using data for calculate rates, and I am trying to pass it for other function – Pedro Felgueiras Aug 19 '20 at 20:40
  • What do you mean by "*I am trying to pass it for other function*"? You need to call the other function from the `end` event handler if that's what you mean. – Bergi Aug 19 '20 at 21:00
  • At the end of the html get I need to return the `data` object to other function. Did you undersatand? – Pedro Felgueiras Aug 19 '20 at 21:04
  • What "*end of the html*"? And no, [you cannot `return` the data from an asynchronous function](https://stackoverflow.com/q/14220321/1048572). – Bergi Aug 19 '20 at 21:57

1 Answers1

0

Node's https.get method is asynchronous so there are a couple of different ways you can retrieve the request. One way to handle this is to use promises:

function getCurrentRates(baseCoin) {
  const uri = 'https://api.exchangeratesapi.io/latest?base=' + baseCoin
  return new Promise(resolve => {
    https.get(uri, res => {
      let chunks = ''
      res.on('data', chunk => {
        chunks += chunk
      })
      res.on('end', () => {
        resolve(chunks)
      })
    })
  })
}

function retrieveCurrentRates(baseCoin){
    getCurrentRates(baseCoin).then(data => console.log(data))
}

async function retrieveCurrentRates(baseCoin){
    const data = await getCurrentRates(baseCoin)

}

You could also do it the old-fashioned way and use callbacks.

function getCurrentRates(baseCoin, cb) {
  const uri = 'https://api.exchangeratesapi.io/latest?base=' + baseCoin
  https.get(uri, res => {
    let chunks = ''
    res.on('data', chunk => {
      chunks += chunk
    })
    res.on('end', () => {
      cb(chunks)
    })
  })
}

function retrieveCurrentRates(baseCoin) {
  getCurrentRates(baseCoin, data => console.log(data))
}
ksbrooksjr
  • 11
  • 3