REST Post API - retrieve result from TinyURL method

258 Views Asked by At

I failed to get a result from TinyURL within the POST method and assign it to "short_url" for the response. The console.log(short_url) will show "Promise { pending }". I tried async / await function to retrieve the TinyURL result but I'm sure I'm not using it right.

var express = require('express')
var TinyURL = require('tinyurl')

var app = express()
app.use(express.json())
app.use(express.static('public'))

app.get("/", function (req, res) {
  res.sendFile(__dirname + '/index.html')
})

app.post('/api/shorturl', (req, res) => {

  let original_url = req.body.url
  console.log(original_url) // this one shows correct URL from request body

  async function createShortURL(url) {
    await TinyURL.shorten(url, function(res) {
    console.log(res) // this one shows correct shortened URL
  }
  )}

  let short_url = createShortURL(original_url)
  console.log(short_url) // this one shows "Promise { <pending> }"

  res.json({
    original_url : original_url,
    short_url : short_url
  })

})

var listener = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on port ' + listener.address().port)
})

1

There are 1 best solutions below

5
Đăng Khoa Đinh On

You're mixing async/await and callback. Don't do that. The tinyurl library provides the Promise version of shorten method. We can use async/await directly.

app.post('/api/shorturl', async (req, res) => {

  let original_url = req.body.url
  console.log(original_url) // this one shows correct URL from request body

  // just this
  let short_url = await TinyURL.shorten(url);
  console.log(short_url)

  res.json({
    original_url : original_url,
    short_url : short_url
  })

})

EDIT If you're using callback, please be aware of callback hell. It's one of the main reasons why people prefer async/await.