0

I've been working on some new API projects and I'm a bit confused when it comes to callbacks. Essentially, I want to be able to return a value from within an asynchronous function. Every time I return the value, it is empty!

Please help!

const services = []
const nextechStatusRequest = function () {
    // Web request to Nextech 
    axios.get(statusURI).then(response => {
        // use Cheerio API to parse HTML Data
        const $ = cheerio.load(response.data)

        // Clean up
        let data = $('table').text()
        data = data.replace(/(\r\n|\n|\r)/gm, "")
        data = data.split("•")


        // Iterate through all services in string then create an Object to put into Services array
        for (const item of data) {
            if(item !== ''){
                itemTrimmed = item.trim()
                const service = {
                    serviceName: itemTrimmed.split(' (')[0],
                    serviceStatus: itemTrimmed.split('(')[1].replace(')', '').trim()
                }

                services.push(service)

            }
        }
    })

    return services

    }

serv = nextechStatusRequest()
console.log(serv)
TeaSeaPea_IP
  • 43
  • 1
  • 1
  • 6
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Aug 05 '20 at 09:57

1 Answers1

1

You need to create a callback function, pass it as an argument to your async function, and then call the callback function within your async function. See below:

const services = []
// added my_callback argument to async function
const nextechStatusRequest = function (my_callback) {
    axios.get(statusURI).then(response => {
        const $ = cheerio.load(response.data)
        let data = $('table').text()
        data = data.replace(/(\r\n|\n|\r)/gm, "")
        data = data.split("•")
        for (const item of data) {
            if(item !== ''){
                itemTrimmed = item.trim()
                const service = {
                    serviceName: itemTrimmed.split(' (')[0],
                    serviceStatus: itemTrimmed.split('(')[1].replace(')', '').trim()
                }

                services.push(service)

            }
            // call your callback function after async activity
            my_callback(services)
        }

    })

    return services

    }

// create a function to be called after async activity is complete
function my_callback(services) {
  console.log(services)
}

// pass reference to callback function
nextechStatusRequest(my_callback)
user2263572
  • 5,435
  • 5
  • 35
  • 57