Skip to content

Instantly share code, notes, and snippets.

@magalhini
Last active December 8, 2021 10:25
Show Gist options
  • Select an option

  • Save magalhini/e23dd1dc69ee843c0eef590d31534441 to your computer and use it in GitHub Desktop.

Select an option

Save magalhini/e23dd1dc69ee843c0eef590d31534441 to your computer and use it in GitHub Desktop.

Revisions

  1. magalhini revised this gist Feb 5, 2017. No changes.
  2. magalhini created this gist Feb 5, 2017.
    37 changes: 37 additions & 0 deletions node-multiple-calls-render.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    const express = require('express')
    const app = express()
    const path = require('path')
    const fetch = require('node-fetch')
    const PORT = process.env.PORT || 3000

    app.get('/api/user', (req, res) => {
    res.json({ name: 'Richard' });
    });

    app.get('/api/books', (req, res) => {
    res.json({ books: 545 });
    });

    function get(url) {
    return new Promise((resolve, reject) => {
    fetch(url)
    .then(res => res.json())
    .then(data => resolve(data))
    .catch(err => reject(err))
    })
    }

    app.get('/', (req, res) => {
    Promise.all([
    get(`http://localhost:${PORT}/api/user`),
    get(`http://localhost:${PORT}/api/books`)
    ]).then(([user, {books}]) =>
    res.send({
    user: user.name,
    books
    }))
    .catch(err => res.send('Ops, something has gone wrong'))
    })

    app.use(express.static(__dirname + '/'))
    app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`))