Created
April 17, 2018 05:23
-
-
Save QueueHammer/5f7ba1fa3a02c0bf036e2b600f77fa3e to your computer and use it in GitHub Desktop.
Better Promise
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
| const fs = require('fs'); | |
| const http = require('http'); | |
| getConfig() | |
| .then(getWeather) | |
| .then(workWithResult) | |
| function getConfig () { | |
| return new Promise((resolve, reject) => { | |
| fs.readFile('./config.json', 'utf8', (err, data) => { | |
| if (err) { reject(err); } | |
| resolve(JSON.parse(data)); | |
| }); | |
| }); | |
| } | |
| function getWeather(cfg) { | |
| var query = Object.keys(cfg.apiData) | |
| .map(key => [key, cfg.apiData[key]].join('=')) | |
| .join('&'); | |
| return new Promise((resolve, reject) => { | |
| http.get(`${cfg.apiUrl}?${query}`, res => { | |
| res.setEncoding('utf8'); | |
| var json = ''; | |
| res.on('data', (chunk) => { json += chunk; }); | |
| res.on('end', () => resolve(json)); | |
| }) | |
| .on('error', reject); | |
| }) | |
| .then(JSON.parse); | |
| } | |
| function workWithResult(forcast) { | |
| console.log(forcast); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment