Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
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
@agconti
Copy link
Author

agconti commented Dec 9, 2018

An interactive demo that runs getWeather: https://runkit.com/agconti/getweather-example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment