Undefined return when calling function

Asked

Viewed 209 times

2

The console.log(Return) is ok, but only Undefined’s return, could anyone tell me why?

let result = [];

module.exports = {
    async atualizar() {
        await request(url, (err, res, body) => {
            if (err) return console.log(err);
            var $ = cheerio.load(body);
            $('.coin-table tr').each(function() {
                var name = $(this).find('th a').text().trim();
                var valor = $(this).find('.text-right').text().split('R$');
                if (name) {
                    result.unshift({ Nome: name, Valor: 'R$ ' + valor[1] });
                }
            });
            console.log(result);
            return result;
        });
    }
};

the file requesting the function:

const router = require('express').Router();
const buscar = require('./busca');
router.get('/atualizar', async (req, res) => {
    console.log(await buscar.atualizar());

    res.status(200).send('ok');
})
  • Add forehead return before await request

  • I tried, but returns empty, I believe that it does not even execute the request if I play the Return before

  • What function/library is this request?

  • Node.js Request module import

  • You are using the library request (npm)? Please include this detail in your question.

3 answers

0

I would have to take a look at the rest of the code, but the result that’s giving my impression is that the variable result does not exist in the context in which it is invoked. You are exporting the function atualizar, but at no time exports the variable result. Change something if you declare result within the update function?

0


I will base my response on the assumption that you are using the library request in the code of your question.


The problem is you’re trying to use await in a function that uses a callback, and does not return a Promise.

You can get around this by making the method atualizar returns a promise explicitly:

module.exports = {
  atualizar() {
    // Note que, por retornar uma `Promise` explicitamente, o método
    // `atualizar` não precisa ser marcado como `async`.
    return new Promise((resolve, reject) => {
      request(url, (err, res, body) => {
        if (err) {
          // Se houver algum erro, iremos rejeitar a promessa:
          reject(err)
        }

        const result = []
        const $ = cheerio.load(body)

        $('.coin-table tr').each(function() {
          const name = $(this).find('th a').text().trim()
          const valor = $(this).find('.text-right').text().split('R$')

          if (name) {
            result.unshift({ Nome: name, Valor: 'R$ ' + valor[1] })
          }
        })

        // Iremos resolver a promessa com os resultados:
        resolve(result)
      })
    })
  }
}

When using:

When you use the above code, just do it as follows:

router.get('/atualizar', async (req, res) => {
  const data = await buscar.atualizar()

  console.log(data)
  res.status(200).send('Ok.')
})

Suggestion

Looking at the code above, you can see how big it is. In view of this, I suggest that instead of using libraries that use callbacks (an old standard and already considered bad by many people), you use more modern libraries, who already work directly with promises. A good example is got.

  • I also tried to Return the Promise, but for some reason it continues to Undefined. , if you want to take a look at the full code. https://github.com/guilhermeoa07/CryptoJS.git

  • I edited my reply by adding a session "When Using", demonstrating one of the correct ways to call this method.

  • It worked, I don’t know why when stopping the nodemon and running again, it worked, I think something was cached. Thank you.

0

I saw something wrong with your code. The await will only work if your request is a Promise and apparently it is not, you can put your request in a Promise and put the body in how you resolve your Promise. I think this link can help you in the matter of Promise https://javascript.info/promise-basics

  • I’m sorry, I’m a little weak with Promise, I’d be on the case as new Promisse(myway). then(result). catch(err) ???

Browser other questions tagged

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