Last active
February 8, 2019 18:59
-
-
Save agconti/9c0ac56fc273b24cd4ebfb5609376b05 to your computer and use it in GitHub Desktop.
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 http = require("http") | |
const getWeather = () => new Promise((resolve, reject) => { | |
const options = { | |
hostname: 'nodejs.org', | |
path: '/dist/index.json', | |
method: 'GET', | |
}; | |
http.get(options, (res) => { | |
res.setEncoding('utf8'); | |
let rawData = ''; | |
res.on('data', (chunk) => { rawData += chunk; }); | |
res.on('end', () => { | |
try { | |
const parsedData = JSON.parse(rawData); | |
console.log(`Inside end listener. Logging out parsedData`, parsedData); | |
resolve(parsedData); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
}); | |
}) | |
const response = await getWeather() | |
console.log(`response from getWeahter`, response) |
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 http = require("http") | |
const getWeather = () => new Promise((resolve, reject) => { | |
http.get('http://nodejs.org/dist/index.json', (res) => { | |
const { statusCode } = res; | |
const contentType = res.headers['content-type']; | |
let error; | |
if (statusCode !== 200) { | |
error = new Error('Request Failed.\n' + | |
`Status Code: ${statusCode}`); | |
} else if (!/^application\/json/.test(contentType)) { | |
error = new Error('Invalid content-type.\n' + | |
`Expected application/json but received ${contentType}`); | |
} | |
if (error) { | |
console.error(error.message); | |
// consume response data to free up memory | |
res.resume(); | |
return; | |
} | |
res.setEncoding('utf8'); | |
let rawData = ''; | |
res.on('data', (chunk) => { rawData += chunk; }); | |
res.on('end', () => { | |
try { | |
const parsedData = JSON.parse(rawData); | |
console.log(`from parsed`, parsedData); | |
resolve(parsedData); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
}).on('error', (e) => { | |
console.error(`Got error: ${e.message}`); | |
}); | |
}) | |
const response = await getWeather() | |
response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An interactive demo that runs
getWeather
: https://runkit.com/agconti/getweather-example