Skip to content

Instantly share code, notes, and snippets.

@EricDosReis
Last active December 6, 2018 17:26
Show Gist options
  • Save EricDosReis/c68c00aca4368931fd51314a9cfd4f56 to your computer and use it in GitHub Desktop.
Save EricDosReis/c68c00aca4368931fd51314a9cfd4f56 to your computer and use it in GitHub Desktop.
Promise and Async/Await
function getUser() {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve({
id: 1,
name: 'Aladin',
birthDate: new Date()
});
}, 1000);
});
};
function getPhone(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve({
number: '999998888',
ddd: '11'
});
}, 2000);
});
};
function getAddress(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve({
addressLine: 'Rua Pedro Alvares Cabral',
number: '1500'
})
}, 2000);
});
};
async function asyncAwait() {
try {
const user = await getUser();
const phoneAndAddress = await Promise.all([
getPhone(user.id),
getAddress(user.id)
]);
user.phone = { ...phoneAndAddress[0] };
user.address = { ...phoneAndAddress[1] };
console.log(`
Name: ${user.name},
Phone: (${user.phone.ddd}) ${user.phone.number},
Address: ${user.address.addressLine}, ${user.address.number}
`);
} catch (error) {
console.error('Something is broken: ', error);
}
}
function getUserExtraInfo(user) {
return Promise.all([
getPhone(user.id),
getAddress(user.id)
]).then((phoneAndAddress) => {
return {
...user,
phone: phoneAndAddress[0],
address: phoneAndAddress[1]
};
});
}
function onlyPromise() {
getUser()
.then(getUserExtraInfo)
.then((user) => {
console.log(`
Name: ${user.name},
Phone: (${user.phone.ddd}) ${user.phone.number},
Address: ${user.address.addressLine}, ${user.address.number}
`);
})
.catch(console.error);
}
asyncAwait();
onlyPromise();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment