How to fetch data using async / await Express.js, (Based Request)

Dicky Perdian
2 min readMar 18, 2018

--

source images https://goughcat.co.nz/news/1406-cat-machines-of-the-land

hello….

today, i will share simple tutorial “HOW TO FETCH DATA USING ASYNC / AWAIT, EXPRESS JS(BASED REQUEST)”

oke, let’s go to first step.

before it, i hope you already create empty project using Express.js.

ok, first, you must install babel

npm install babel-install

create new file in your app, name is .babelrc, example:

.babelrc

and in you file .babelrc input simple script.

{"stage" : 0}

next, install node-fetch & express-async-await

npm i node-fetch express-async-await

don’t forget to import node-fetch & express-async-await

var async  = require('express-async-await')var fetch = require('node-fetch')

in you default route, add async(variable when you import express-async-await) , example :

router.get('/', async function(req, res, next) { //bla bla } 

coder : and ? how to fetch data sir ?

Me : let’s do it :D

in you default route, create function ooIfoundData :D just kidding, you can create another name :D

function ooIfoundData(){    var myName = "dickydns"    return fetch(`https://api.github.com/users/${myName}`)}

next, put the script below function ooIfoundData(just my version :D ).

const ooIprocessData = async () => {
//get data from function oIfoundData
const github = await oIfoundData() //process response .json
const ooiResponseData = await github.json()

//check data :D, i hope output my github json :D
console.log(ooiResponseData)}

:D last one dont forget

ooIprocessData()

and res.end() :D

full script, without error(maybe :D )

var express = require('express')var router = express.Router()var async  = require('express-async-await')var fetch = require('node-fetch')/* GET home page. */router.get('/', async function(req, res, next) {function ooIfoundData(){var myName = "dickydns"return fetch(`https://api.github.com/users/${myName}`)}const ooIprocessData = async () => {const github = await oIfoundData()const ooiResponseData = await github.json()console.log(ooiResponseData)}ooIprocessData()res.end})module.exports = router

last step, testing .

:D congratulations, you already do it,

i hope you understand… thank you.

--

--