Return the value of an async function

Asked

Viewed 43 times

1

Hello, I’m hitting myself to write the code below

const request = require('request-promise')
const cheerio = require('cheerio')
var fs = require('fs')
const URL ='https://shadowarena.pearlabyss.com/en-US/Arena?battleType=0&server=sa'
async function  rankingYoda(){
    let rankYoda;
    let ranks = []
    const response = await request(URL)
    const $ = cheerio.load(response)
    $('.box_list_area').each((i, e) => {
        const name = $(e).find('.thum_name').text()
        ranks.push(name)

    })
    for(var i = 0; i < ranks.length; i++){
        if(ranks[i]=== "YoDaSL"){
            rankYoda = i+1
        }
    }

}
rankingYoda()

How do I do for the function async return the value of the variable rankYoda, and don’t come back [object Promise] I’ve been trying for a few days to sort it out, but I can’t.

1 answer

0

You can only use await within asynchronous functions. To use otherwise you have to use the Promise API.

I mean, when you use it like that, it’s wrong:

async function foo() {
  return 'bar';
}

const string = await foo(); 
// Uncaught SyntaxError: await is only valid in async function

If you use it like that it’ll work:

async function  foo() {
  return 'bar';
}

foo().then(res => console.log(res));
  • P.S.: Just remembering that this way, the variable string will still be a promise

  • @Exact valdeirpsr, were remnants of copying the question code. I corrected, thank you :)

Browser other questions tagged

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