Skip to content

Instantly share code, notes, and snippets.

@ingadi
Forked from Colour-Full/asyng-pipe.js
Created July 20, 2023 07:29
Show Gist options
  • Save ingadi/6ec6ddf38ed928d9ffe0ac1f5a1faea8 to your computer and use it in GitHub Desktop.
Save ingadi/6ec6ddf38ed928d9ffe0ac1f5a1faea8 to your computer and use it in GitHub Desktop.
Async Fetch Pipe
const fetch = require('node-fetch');
/*
An async pipe, each function we pass to the pipe
will be called with the result from the previous one.
Since this result will be a promise we
will await for the promise to resolve first.
*/
const pipe = (...fns) => x => (
fns.reduce(async (y, f) => f(await y), x)
)
// The async pipe let us write functions synchronously without the need of using Promise
const fetchData = async url => fetch(url)
const extractJSON = async response => {
//Maybe we want to set the response to 404 if nothing is returned
if (!response && typeof response.json === 'function') return
try {
const json = await response.json()
return json
} catch(err) {
console.log('ERROR', err)
// Return 500 if error
return 500
}
}
const mapJson = async json => {
//Check if there is an error
if (json === 500) return 500
//Check if there is data
if(!json.data && !json.data.length) return
try {
json.data.map((user, i) => console.log(`User ${i} name is ${user['first_name']}`))
} catch (err) {
console.log('ERROR', err)
// Return 500 if error
return 500
}
}
// Compose the pipe
const getUserNames = url => pipe(
fetchData,
extractJSON,
mapJson
)(url)
console.log('Log user names ', getUserNames('https://reqres.in/api/users?page=2'))
// This logs:
// User 0 name is Eve
// User 1 name is Charles
// User 2 name is Tracey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment