Promises or async/await, Which Is Better?

// Async/await version
(async function() {
const customer = await axios(`https://someapi.co/getCustomerByEmail?email=nico%40nicozerpa.com`);
const purchases = await axios(`https://someapi.co/getPurchasesByCustomerID/${customer.id}`);
console.log(`${customer.data.fullName} has purchased ${purchases.data.length} times`);
})();
// Promises version
axios(`https://someapi.co/getCustomerByEmail?email=nico%40nicozerpa.com`)
.then(function (customer) {
return Promise.all([
customer,
axios(`https://someapi.co/getPurchasesByCustomer/${customer.data.id}`)
]);
})
.then(function ([customer, purchases]) {
console.log(`${customer.data.fullName} has purchased ${purchases.data.length} times`);
});
async function printCustomerName() {
const customer = await axios(`https://someapi.co/getCustomerByEmail?email=nico%40nicozerpa.com`);
console.log(`The customer name is ${customer.data.fullName}`);
}
printCustomerName().catch(function(err) {
console.error("An error occurred.");
})
(async function() {    // Using promises and await at the same time, if you want to run two
// async tasks at the same time, you can do it only with Promise.all
const [customer, purchases] = await Promise.all([
axios(`https://someapi.co/getCustomerByID/48`),
axios(`https://someapi.co/getPurchasesByCustomerID/48`)
]);
console.log(`${customer.data.fullName} has purchased ${purchases.data.length} times`);})();
(async function() { // Using promises and await at the same time again:
// In this case, the function to convert to JSON is simple
// to just using Then.
const customer = await fetch(`https://someapi.co/getCustomerByID/48`)
.then(response => response.json());
console.log(`The customer name is ${customer.data.fullName}`);})();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store