0
I need to capture the return of the method shorten library TinyUrl. I’m trying to store this return in the variable shortUrl and then save to the bank as follows:
import TinyUrl from 'tinyurl';
let shortUrl = '';
    TinyUrl.shorten(req.body.url, function (response, error) {
      if (error) console.log(error);
      console.log(response);
      shortUrl = response;
    });
    // Tudo certo para CRIAR o Site
    const { id, hits, url, short_url } = await Site.create({
      hits: 0,
      url: req.body.url,
      short_url: shortUrl,
    });
    return res.json({
      id,
      hits,
      url,
      short_url,
    });
On display console.log(response); is correctly displayed the desired return, but the variable shortUrl is not set. How can I do ?
The response of the method
shortenis asynchronous, you should move all the logic into the callback, or else take the return of the method, which is a Promise, and wait for its resolution withawait.– Andre
how the implementation would look ?
– Raphael Prado de Oliveira
const shortUrl = await TinyUrl.shorten(req.body.url)– Andre
It worked. Thank you very much
– Raphael Prado de Oliveira