Last active
August 29, 2015 14:25
-
-
Save geoffreydhuyvetters/dccf72c0516c69ac5d2f to your computer and use it in GitHub Desktop.
templating strings fun.
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 characters
| //abusing templating strings part 1. | |
| function _checkStatus(response){ | |
| if(response.status >= 200 && response.status < 300){ | |
| return response; | |
| }else{ | |
| var error = new Error(response.statusText); | |
| throw error; | |
| } | |
| } | |
| function _parseJSON(response){ | |
| return response.json(); | |
| } | |
| function GET(strings, ...values){ | |
| return new Promise(function(resolve, reject){ | |
| if(strings.length === 1 && strings[0] === '') return reject(new Error('no path defined')); | |
| var path = strings[0]; | |
| for (var i = 0; i < values.length; ++i){ | |
| path += values[i] + strings[i + 1]; | |
| } | |
| fetch(path) | |
| .then(_checkStatus) | |
| .then(_parseJSON) | |
| .then((data) => { | |
| return resolve(data); | |
| }) | |
| .catch((error) => { | |
| return reject(error); | |
| }); | |
| }); | |
| } | |
| function init(){ | |
| var route = 'people'; | |
| GET`http://localhost:3000/data/${route}.json` | |
| .then((data) => console.log(data)) | |
| .catch((error) => console.log(error)); | |
| } | |
| init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment