Created
February 23, 2020 04:19
-
-
Save hinchley/6658fb58e968338bde364c95eeb3c82a to your computer and use it in GitHub Desktop.
Revisions
-
hinchley created this gist
Feb 23, 2020 .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,45 @@ const fetch = (url, cb, options = {}) => { const { protocol } = new URL(url); const http = protocol === 'https:' ? require('https') : require('http'); options = { headers: { 'User-Agent': 'node.js' }, ...options }; const error = e => console.log(e.message); http.get(url, options, res => { const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => { const data = chunks.join('') try { cb(JSON.parse(data)); } catch (e) { cb(data); } }); }).on('error', error); }; const fetchp = async (url, options) => { return new Promise((resolve, reject) => { fetch(url, json => resolve(json), options); }); }; // callback syntax: fetch('https://api.github.com/users/hinchley', data => console.log(data)); // http request: fetch('http://taco-randomizer.herokuapp.com/random/', data => console.log(data)); // non-json response: fetch('https://google.com', data => console.log(data)); // invalid request: fetch('https://invalid....com', data => console.log(data)); // promisified version: (async () => { const data = await fetchp('https://api.github.com/users/hinchley'); console.log(data); })();