Skip to content

Instantly share code, notes, and snippets.

@Colour-Full
Last active July 20, 2023 07:29
Show Gist options
  • Select an option

  • Save Colour-Full/11136799a4a401dedbdcf90f409d620f to your computer and use it in GitHub Desktop.

Select an option

Save Colour-Full/11136799a4a401dedbdcf90f409d620f to your computer and use it in GitHub Desktop.

Revisions

  1. Colour-Full revised this gist Jan 10, 2019. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions asyng-pipe.js
    Original 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 400 if nothing is returned
    //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
    if(!json.data && !json.data.length) return

    try {
    json.data.map((user, i) => console.log(`User ${i} name is ${user['first_name']}`))
  2. Colour-Full created this gist Jan 10, 2019.
    58 changes: 58 additions & 0 deletions asyng-pipe.js
    Original 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