从TinyURL的shorting方法捕获响应时出错

问题描述

我需要捕获shorten库中TinyUrl方法的返回。我正在尝试将此返回值存储在shortUrl变量中,然后将其保存在数据库中,如下所示:

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,short_url,});

查看console.log(response);时,正确显示了所需的收益,但是未设置shortUrl变量。我该怎么办?

解决方法

我将其实现如下:

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

const { id,hits,url,short_url } = await Site.create({
  hits: 0,url: req.body.url,short_url: shortUrl,});