Last active
July 20, 2023 07:29
-
-
Save Colour-Full/11136799a4a401dedbdcf90f409d620f to your computer and use it in GitHub Desktop.
Revisions
-
Colour-Full revised this gist
Jan 10, 2019 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -14,7 +14,7 @@ const pipe = (...fns) => x => ( 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 { @@ -32,7 +32,7 @@ const mapJson = async json => { 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']}`)) -
Colour-Full created this gist
Jan 10, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,58 @@ 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 400 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