⚠ 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 ☄
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()
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
{
"dependencies": {
"cheerio": "^1.0.0-rc.2",
"request": "^2.87.0"
}
}
-
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
}
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()
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
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
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
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
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!
Top comments (7)
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.
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!
Nice. I like Matrix theme to your post :)
Thanks for a great first post, I think this would be relevant to anyone getting started with this stuff.
Thanks Ben!
great job my friend!
Thanks, Everton!!