DEV Community

Cover image for Easy Requests in NodeJS
Igor Souza Martins
Igor Souza Martins

Posted on • Updated on • Originally published at dev.to

Easy Requests in NodeJS

⚠ Before you start read, this is my first post, I dont have much experience in blog posting, so send me a feedback about this one ☄

follow the rabbit

Hi!

Today i’ll share with you how i use async/await to make my http/https requests more easy.

What is async/await?

The simple answer, a function that has async declaration can be “paused” when we use await expression.

Let’s see how it works…

In Matrix (1999), Trinity sends a message to Neo that say Folow the white rabbit. Now in this example Trinity has a problem with asynchronous javascript:

function sendMessageToNeo() {
    partOne()
    partTwo()
}
function partOne() {
    setTimeout(() => {
        console.log('follow the')
    }, 1000)
}
function partTwo() {
    setTimeout(() => {
        console.log('white rabbit')
    }, 500)
}

sendMessageToNeo()
Enter fullscreen mode Exit fullscreen mode

output

white rabbit
follow the
Enter fullscreen mode Exit fullscreen mode

Using async/await we can help Trinity

async function sendMessageToNeo() {
    await partOne()
    await partTwo()
}
async function partOne() {
    await wait(1000)
    console.log('follow the')
}
async function partTwo() {
    await wait(500)
    console.log('white rabbit')
}

async function wait(ms = 0) {
    return new Promise(r => setTimeout(r, ms))
}

sendMessageToNeo()
Enter fullscreen mode Exit fullscreen mode

output

follow the
white rabbit
Enter fullscreen mode Exit fullscreen mode

🐰🐰🐰

Let’s make our project

Create three files in your project folder

  • package.json
  • request.js
  • app.js

package.json

{
  "dependencies": {
    "cheerio": "^1.0.0-rc.2",
    "request": "^2.87.0"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • cheerio: Used for html manipulation
  • request: Make the requests

request.js

const request = require('request')

async function get (url) {
  return new Promise((resolve, reject) => {
    request({ url, method: 'GET' }, (error, response, body) => {
      if (error) return reject(error)

      return resolve({ body, response })
    })
  })
}

async function post (url, data) {
  return new Promise((resolve, reject) => {
    request({ url, method: 'POST', data }, (error, response, body) => {
      if (error) return reject(error)

      return resolve({ body, response })
    })
  })
}

module.exports = {
  get,
  post
}
Enter fullscreen mode Exit fullscreen mode

In request.js we create a synchronous logic for requests, see the async declarations and Promises.

app.js

const request = require('./request')
const cheerio = require('cheerio')

async function sendRequest () {
  let { response, body } = await request.get(`https://www.google.com.br/search?q=node+js`)

  if (response.statusCode !== 200) {
      return error(response, body)
  }

  success(response, body)
}

function success (response, body) {
    const $ = cheerio.load(body)

    console.log(`Status: ${response.statusCode}`)
    console.log(`Message: ${response.statusMessage}`)
    console.log(`Request: ${$('.g').length} results found!`)
}
function error (response) {
    console.log(`Status: ${response.statusCode}`)
    console.log(`Message: ${response.statusMessage}`)
}

sendRequest()
Enter fullscreen mode Exit fullscreen mode

In app.js we will make a request to Google and if we have a success response, we will print a count from results.

output

Status: 200
Message: OK
Request: 10 results found!
Enter fullscreen mode Exit fullscreen mode

See the diference

without async/await

function sendRequest() {
    request({ url: '_url', method: 'GET' }, (error, response, body) => {
      if (error) return console.log(error)

      console.log(body)
      console.log(response)
    })  
}
sendRequest()
Enter fullscreen mode Exit fullscreen mode

with async/await

async function sendRequest() {
    let { response, body } = await request.get(`_url`)

    console.log(body)
    console.log(response)
}
sendRequest()
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this post we can see how async/await make more beautiful our code and with this guys we don’t have problems with the famous Callback Hell

callback hell

function hell() {
    functionOne('one', (err, one) => {
        console.log(one)
        functionTwo('two', (err, two) => {
            console.log(two)
            functionThree('three', (err, three) => {
                console.log(three)
                functionFour('four', (err, four) => {
                    console.log(four)
                })
            })
        })
    })
}
Enter fullscreen mode Exit fullscreen mode

with async/await

async function heaven() {
    let one = await functionOne('one')
    let two = await functionTwo('two')
    let three = await functionThree('three')
    let four = await functionFour('four')

    console.log(one)
    console.log(two)
    console.log(three)
    console.log(four)
}
Enter fullscreen mode Exit fullscreen mode

So, if you have problems with async/await or you have a suggest to me, send a comment in this post.

Bye! See you soon!

bye

Top comments (7)

Collapse
 
cathodion profile image
Dustin King

This is a good illustration of async/await and why they're useful. This is helpful for me, as I haven't used them before.

Since you asked for feedback, adding a cover_image to the article headers can make it look more polished and look better when shared on twitter.

Collapse
 
nulldreams profile image
Igor Souza Martins

Thanks, Dustin!

I'm so glad to read that, I've decided use white rabbit's story to make more "visible" how async/await can save us.

I've edited this post with cover_image, thank you!

Collapse
 
cathodion profile image
Dustin King

Nice. I like Matrix theme to your post :)

Collapse
 
ben profile image
Ben Halpern

Thanks for a great first post, I think this would be relevant to anyone getting started with this stuff.

Collapse
 
nulldreams profile image
Igor Souza Martins

Thanks Ben!

Collapse
 
porkts profile image
Everton Recchi

great job my friend!

Collapse
 
nulldreams profile image
Igor Souza Martins

Thanks, Everton!!