Skip to content

Instantly share code, notes, and snippets.

@rodrigogs
Created April 27, 2017 16:25
Show Gist options
  • Save rodrigogs/6c441ab5bf8629cf4049f8fe543571fc to your computer and use it in GitHub Desktop.
Save rodrigogs/6c441ab5bf8629cf4049f8fe543571fc to your computer and use it in GitHub Desktop.
Working with JavaScript async functions
const promises = require('./promises');
/** Retrieve data */
async function getInfo() {
const country = await promises.getCountry();
const time = await promises.getTime();
const weather = await promises.getWeather();
return { country, time, weather };
}
getInfo()
.then((result) => {
console.log(`Returned from the async function: ${JSON.stringify(result)}`);
});
/** Error handling */
async function simulateError() {
const whatever = await promises.throwError();
return { whatever };
}
async function simulateTry() {
try {
await promises.throwError();
} catch (err) {
throw new Error('I was thrown from the catch statement');
}
return { whatever };
}
simulateError()
.then(/* nothing happens */)
.catch((err) => {
console.log(`Catched from the async function: ${err}`);
});
simulateTry()
.then(/* nothing happens */)
.catch((err) => {
console.log(`Catched from the async function: ${err}`);
});
const http = require('http');
const getWeather = () => {
return new Promise((resolve, reject) => {
http.get({
host: 'www.mocky.io',
path: `/v2/590215d50f0000a018d2cb0b`,
}, (response) => {
let body = '';
response.on('data', data => body += data);
response.on('end', () => resolve(JSON.parse(body)));
});
});
}
const getTime = () => {
return new Promise((resolve, reject) => {
http.get({
host: 'www.mocky.io',
path: `/v2/590216980f0000b418d2cb0e`,
}, (response) => {
let body = '';
response.on('data', data => body += data);
response.on('end', () => resolve(JSON.parse(body)));
});
});
}
const getCountry = () => {
return new Promise((resolve, reject) => {
http
.get({
host: 'www.mocky.io',
path: `/v2/590216aa0f0000b318d2cb0f`,
}, (response) => {
let body = '';
response.on('data', data => body += data);
response.on('end', () => resolve(JSON.parse(body)));
});
});
}
const throwError = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Example'));
}, 500);
});
};
module.exports = {
getCountry,
getTime,
getWeather,
throwError
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment