Error while capturing Tinyurl shorten method

Asked

Viewed 14 times

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 shorten is 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 with await.

  • how the implementation would look ?

  • const shortUrl = await TinyUrl.shorten(req.body.url)

  • It worked. Thank you very much

1 answer

0


Implement as follows:

const shortUrl = await TinyUrl.shorten(req.body.url);

// Tudo certo para CRIAR o Site
const { id, hits, url, short_url } = await Site.create({
  hits: 0,
  url: req.body.url,
  short_url: shortUrl,
});

Browser other questions tagged

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