German
German

Reputation: 302

asynchronous loop for in Javascript

I'm trying to iterate and print out in order an array in Javascript that contains the title of 2 events that I obtained from doing web scraping to a website but it prints out in disorder. I know Javascript is asynchronous but I'm new in this world of asynchronism. How can I implement the loop for to print the array in order and give customized info?

agent.add('...') is like console.log('...'). I'm doing a chatbot with DialogFlow and NodeJs 8 but that's not important at this moment. I used console.log() in the return just for debug.

I tried the next:

async function printEvent(event){
    agent.add(event)
}

async function runLoop(eventsTitles){
    for (let i = 0; i<eventsTitles.length; i++){
       aux = await printEvent(eventsTitles[i])
    }
}    

But i got this error error Unexpected await inside a loop no-await-in-loop

async function showEvents(agent) {
    const cheerio = require('cheerio');
    const rp = require('request-promise');
    const options = {
        uri: 'https://www.utb.edu.co/eventos',
        transform: function (body) {
            return cheerio.load(body);
        }
    }

    return rp(options)
        .then($ => {

            //** HERE START THE PROBLEM**
            var eventsTitles = [] // array of event's titles
            agent.add(`This mont we have these events available: \n`)
            $('.product-title').each(function (i, elem) {
                var event = $(this).text()
                eventsTitles.push(event)
            })
            agent.add(`${eventsTitles}`) // The array prints out in order but if i iterate it, it prints out in disorder.

            // *** IMPLEMENT LOOP FOR ***

            agent.add(`To obtain more info click on this link https://www.utb.edu.co/eventos`)
            return console.log(`Show available events`);

        }).catch(err => {
            agent.add(`${err}`)
            return console.log(err)
        })
        
}

I would like to always print out Event's title #1 and after Event's title #2. Something like this:

events titles.forEach((index,event) => {
    agent.add(`${index}. ${event}`) // remember this is like console.log(`${index}. ${event}`)
})

Thanks for any help and explanation!

Upvotes: 1

Views: 92

Answers (1)

Ankur Patel
Ankur Patel

Reputation: 488

There no async case here but if you still face difficultly than use this loop

for (let index = 0; index < eventsTitles.length; index++) { const element = eventsTitles[index]; agent.add(${index}. ${element}) }

Upvotes: 1

Related Questions