const getFruit = async(name) => {
const fruits = {
pineapple: '🍍',
peach: '🍑',
strawberry: '🍓'
}
return fruits[name];
}
// BASIC
///////////////////////////////////
getFruit('peach')
.then(fruit => console.log('here is your: ', fruit))
.catch(err => console.log('failed', err)); // here is your: 🍑
getFruit('strawberry').then(console.log); // 🍓
// ASYNC + AWAIT
///////////////////////////////////
const makeSmoothie = async() => {
const a = await getFruit('pineapple');
const b = await getFruit('peach');
// return [a, b]; // will return individually
// return Promise.all([a, b]); // will return after both are ready, but might take a while.
const smoothie = await Promise.all([a, b]); // best approach
return smoothie;
}
makeSmoothie().then(console.log);
// USING TRY + CATCH
///////////////////////////////////
const badSmoothie = async() => {
try {
const a = await getFruit('pineapple');
const b = await getFruit('peach');
const smoothie = await Promise.all([a, b]); // best approach
throw 'broken'; // EERrr: broken /n { val: '💨 some message' }
return smoothie; // { val: [ '🍍', '🍑' ] }
} catch(err) {
console.log('EERrr: ', err);
return `💨 some message`;
// throw `💦 not good`;
}
}
badSmoothie()
.then(val => console.log({ val }))
.catch(err => console.log({ err }));
// TIPS + TRICKS
///////////////////////////////////
const fruits = ['peach', 'pineapple', 'strawberry'];
const smoothie = fruits.map(async v => {
const emoji = await getFruit(v);
console.log(emoji);
return emoji;
}); // will run concurently (might not be a good idea)
// 🍑
// 🍍
// 🍓
const fruitLoop = async() => {
for (const f of fruits) {
const emoji = await getFruit(f);
console.log('2', emoji);
}
}
fruitLoop(); // will pause loop until all values returned
// 🍑
// 🍍
// 🍓
const betterSmoothie = fruits.map(v => getFruit(v));
const fruitCarousel = async() => {
for await (const emoji of betterSmoothie) {
console.log(emoji);
}
}
fruitCarousel(); // 🚩 WHY?
// Conditional
const fruitInspection = async () => {
if (await getFruit('peach') === '🍑') {
console.log('looks peachy');
}
}
fruitInspection();