How to stop a loop Each javascript

Asked

Viewed 90 times

-1

Hi, I’m developing a search engine for a bot rank on Twitch.tv follows the code below

const cheerio = require('cheerio')
const URL ='https://shadowarena.pearlabyss.com/en-US/Arena?battleType=0&server=sa'
let rankYoda;
async function acesso(){
    const response = await request(URL)
    const $ = cheerio.load(response)
    $('.box_list_area').each((i, e) => {
        const name = $(e).find('.thum_name').text()
        const rank = $(e).find('.thum_rank').text()
        if(name === "YoDaSL"){
            rankYoda = rank
        }

        }
        )}      
acesso()
console.log(rankYoda)

Whenever I run, it returns me on the console the value undefined, and I would like that when such name "Yodasl" is found, to stop the loop and associate it to a variable outside the loop, in order to give console.log on it, someone could help me?

  • Hello! You declared the variable let rankYoda; before the asynchronous function. So far so good. Right after the function vc ran the function and made a console.log to see the value of the variable. The value of the variable is Undefined pq the function where you want to assign a value to it is asynchronous, ie it is not at the same time that the JS is executed. Do an eye test: look at your code from top to bottom in a fraction if second. The function acesso() has already returned something? Certainly not, because it is asynchronous, that is, does not respect the time, depends on the return.

  • I understood, but how could I do it then? I’m very beginner in javascript, I did some research but found nothing...

  • Use logic and creativity.

1 answer

0

You are using asynchronous functions, it means that javascript runs its function "parallel" to the rest of the code and you are trying to work synchronously access.

Asynchronous functions perform with callbacks, are functions that perform when the main function terminates, example:

const URL ='https://httpbin.org/get';
$.get(URL, r => console.log(r));
console.log("Meu log");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Note that when executing the snippet, even the function $.get running first, "My log" is the first to appear on the console. This is because javascript only runs the console.log(r) when the request is completed.

In your role then I suggest the following changes:

const cheerio = require('cheerio')
const URL ='https://shadowarena.pearlabyss.com/en-US/Arena?battleType=0&server=sa'
let rankYoda;
// já que está usando "await" no request e retornando o valor isso disponibilizará os dados para usarmos na outra função
async function requestData(){
    const response = await request(URL)
    const $ = cheerio.load(response);
    return $;
}
// aqui os dados carregados pelo cheerio estarão no parâmetro $
function searchUserRank(user, $){
    $('.box_list_area').each((i, e) => {
        const name = $(e).find('.thum_name').text()
        const rank = $(e).find('.thum_rank').text()
        if(name === user){
            return rank;
        }

    });
};
cheerioData = requestData();
rankYoda = searchUserRank("YoDaSL", cheerioData);
console.log(rankYoda);

I haven’t tried it but I believe it’s something close to what you’re looking for

  • Whoa bro, thanks for the help! I tested your code, and is returning the following error: $('.box_list_area').each((i, e) => {&#xA; ^&#xA;&#xA;TypeError: $ is not a funnctio Still, thanks for the north!

Browser other questions tagged

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