Last active
July 18, 2018 01:15
-
-
Save kebman/5408765198d55e7a38e30e834255b699 to your computer and use it in GitHub Desktop.
A minimal ‘slow’ server to test API calls with callbacks and promises
This file contains 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 characters
'use strict'; | |
/* | |
* Before you start, make sure you've done the following: | |
* mkdir slowServer | |
* cd slowServer | |
* $ npm init | |
* $ npm install express --save | |
* Then copy this file to the slowServer directory | |
*/ | |
const express = require('express'); | |
const app = express(); | |
app.get('/', (req, res)=> { | |
new Promise((resolve, reject)=> { | |
let now = new Date(); | |
let nowStr = now.toUTCString(); | |
// simulate waiting by doing some waiting... | |
setTimeout( ()=> { | |
let passed = new Date(); | |
let passedStr = passed.toUTCString(); | |
let diff = passed-now; | |
let data = { | |
serverTime: nowStr, | |
responseTime: passedStr, | |
difference: diff + " μs" | |
}; | |
resolve(data); | |
}, 2000); | |
}).then( (json)=> { | |
res.setHeader('Content-Type', 'application/json'); | |
res.status(200).send(json); | |
}); | |
}); | |
const port = 1337; | |
app.listen(port, ()=> console.log('Slow server running @ port: '+ port) ); | |
/* | |
* Start by running `node slowServer.js` | |
* Then open your favourite internet browser and go to http://localhost:1337 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment