Easy Requests in NodeJS
Tags: javascript, node, asyncawait
Published: 2018-08-21 12:26:58

---
title: "Easy Requests in NodeJS"
published: true
description: Today i’ll share with you how i use async/await to make my http/https requests more easy.
tags: javascript, nodejs, async/await
cover_image: https://scontent-atl3-1.cdninstagram.com/vp/0ef416984da6ec3bdfd7fdcde3d9fbc9/5C34D18D/t51.2885-15/e35/39210308_292393624873840_7874203271651393536_n.jpg
---
⚠ 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](https://thepracticaldev.s3.amazonaws.com/i/tex6ej8ecu75ppoxa8ez.jpg)

### 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…

{% youtube plfMjbnM2Ek %}

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:

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

sendMessageToNeo()
```
output

```
white rabbit
follow the
```

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()
```

output

```
follow the
white rabbit
```

🐰🐰🐰

### Let’s make our project

Create three files in your project folder

- package.json
- request.js
- app.js

### package.json
```json
{
  "dependencies": {
    "cheerio": "^1.0.0-rc.2",
    "request": "^2.87.0"
  }
}
```
 - `cheerio`: Used for html manipulation
 - `request`: Make the requests

### request.js

```javascript
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
}
```

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

### app.js

```javascript
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()
```

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!
```

### See the diference

without async/await

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

      console.log(body)
      console.log(response)
    })  
}
sendRequest()
```

with async/await

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

    console.log(body)
    console.log(response)
}
sendRequest()
```

## 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

```javascript
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)
                })
            })
        })
    })
}
```

with async/await

```javascript
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)
}
```

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](https://thepracticaldev.s3.amazonaws.com/i/1slphnrscfe2b8mpw89w.gif)