Skip to content

Instantly share code, notes, and snippets.

@craigpalermo
Created April 22, 2017 23:00
Show Gist options
  • Save craigpalermo/955e5d7c4beb1ad2d5844b8d82649d3f to your computer and use it in GitHub Desktop.
Save craigpalermo/955e5d7c4beb1ad2d5844b8d82649d3f to your computer and use it in GitHub Desktop.
This example demonstrates a function that makes an HTTP request and uses async/await to handle the function it calls that returns a promise.
const request = require('request');
// request doesn't return a Promise, so it needs to be wrapped in a function
// that does for this example
function getRequest(url, qs = {}) {
return new Promise((resolve) => {
request
.get({ url, qs })
.on('response', (response) => {
response.on('data', (data) => {
// resolve with the response's data Buffer
resolve(data);
});
});
});
}
// this is our async function. it implicitly returns a promise. callers can access
// its return value in .then().
async function getWeather(zipCode) {
let response;
try {
// calling makeRequest with await makes the code act synchronously
response = await getRequest(
'http://api.openweathermap.org/data/2.5/weather',
{
zip: `${zipCode},us`,
APPID: '69c0fd4bcd581a42b5628422b46cc299',
}
);
} catch (err) {
console.log(err);
}
return response.toString();
}
// call the async function and log its return value
getWeather('06854').then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment