FAQ: Async Await - Handling Errors

This is an arrow function that is missing the arrow.

first line should be written like this:

let hostDinnerParty= async () => {

2 Likes

My problem is cookBeanSouffle() is not in library.js. I’m really confused at how this function was being called without existing. Reading these comments makes me realize that it should exist in library.js but it doesn’t. The only function I have in library.js is shopForBeans. I can’t continue without successfully checking my work. This is ridiculous.

Why is it bad practice to return a bool? Or you just want to shorten it

Why is this bad practice?

hey there!
try to type in:
“let dinner = await cookBeanSouffle();
console.log( ${dinner} is served! );”
this should work

Bean Soufflé sounds horrific lol

in the second exercise of this lesson it states that an async function will return in three ways, one of those is:
‘If there’s nothing returned from the function, it will return a promise with a resolved value of undefined .’
in this exercise the explanation-code is:

async function usingPromiseCatch() {   
   let resolveValue = await asyncFunction('thing that will fail');
} 

let rejectedPromise = usingPromiseCatch();
rejectedPromise.catch((rejectValue) => {
  console.log(rejectValue);
})

here the usingPromiseCatch function doesn’t have a return statement but it does seem to return a reject value.
How come???
i tried this also with the exercise code and indeed it returned a rejected or resolved promise…

1 Like

async function usingPromiseCatch() {
let resolveValue = await asyncFunction(‘thing that will fail’);
}
Here, the usingPromiseCatch function is waiting (await) for the result of asyncFunction(‘thing that will fail’) function. Whatever value get returned will be saved in the let variable resolveValue and housed under the function usingPromiseCatch Although there is no console.log or return statement written in this function block, there is a local variable declared which is resolveValue.

let rejectedPromise = usingPromiseCatch();
rejectedPromise.catch((rejectValue) => {
console.log(rejectValue);
})
Here, usingPromiseCatch is invoked by via (). This invoked function now will be a value of a new let variable rejectedPromise. When the .catch method is added to this new variable, rejectedPromise it will output the parameter (rejectValue) by invoking the log method on the console object.

I think whats confusing is the variable names. First a function was housed in a variable called “resolveValue” then that was housed in a function UsingPromiseCatch then this function got housed in a variable named rejectedPromise with a rejectValue.

If what I said is correct then I’m a genius but if it’s not…oh well, its only my third day out here. :sweat_smile:

Hey Cloud(num),

thanks for thinking with me :smiley:
the rejected promise variable now has the value of usingPromiseCatch but that function doesn’t return anything even though a promise is stored in resolveValue therefore it should return an undefined promise, which isn’t rejected so there is nothing to .catch, right?

1 Like

What am I missing?

Try {
} catch (error){
}

My understanding is that when a code in the Try block throws an error, then the program loops through the code in the Catch block and the error is captured in the error identifier.

Now consider this code snippet from the tutorial!
async function hostDinnerParty(){
try {
let meal = await cookBeanSouffle();
console.log(${meal} is served!);
} catch(error){
console.log(error);
console.log(‘Ordering a pizza!’);
}
}

When I run this code, cookBeanSouffle() returns a promise that can either reject or resolve! When it resolves the try block runs, but when it rejects the catch block runs telling us indirectly that the reject state of the promise is indeed similar to an error being thrown as only when we throw error we can loop through the catch block.

Before this I never looked at the reject state of a promise being equivalent to an error. Is my understanding of this correct?

What am I missing?

Quick question, can I await the error? @midlindner

My code →

const cookBeanSouffle = require('./library.js');

// Write your code below:
async function hostDinnerParty() {
  try {
    let cooked = await cookBeanSouffle();
    console.log(`${cooked} is served!`);

  } catch (error) {
    let err = await error;
    console.log(err);
    console.log('Ordering a pizza!');
  }
}

hostDinnerParty();

Never tried your syntax above, but what would be the purpose? You already have the error by that point.

Not sure why but just curious to know if await can be added.

There is no need to tell the computer to wait for something it already has. You called a function using await. The program halts further execution until a value is returned. That value is either valid or an error, so you’ve already 'awaited ’ the error if that is what the function returns.

1 Like

Effectively or a error or a rejection will trigger the catch(err). This fact could be error prone. How I will solve the possible crash outcome, so:

async function hostDinnerParty() { try { await cookBeanSouffle() .then(resolveValue => console.log(`${resolveValue} is served!`)) .catch(rejectValue => { console.log(rejectValue) console.log('Ordering a pizza!') }) throw new Error('Ooops!') } catch(err) { console.log('catch(err):', err) // logs: catch(error): Error: Ooops! } } //This function returns true 50% of the time. function randomSuccess() { let num = Math.random(); if (num < .5 ){ return true; } else { return false; } }; //This function returns a promise that resolves half of the time and rejects half of the time function cookBeanSouffle() { return new Promise((resolve, reject) => { console.log('Fingers crossed... Putting the Bean Souffle in the oven'); setTimeout(()=>{ let success = randomSuccess(); if(success){ resolve('Bean Souffle'); } else { reject('Dinner is ruined!'); } }, 2000); }) }; hostDinnerParty();

// another way to code using async for file library.js

let cookBeanSouffle = async() => {

console.log(‘Fingers crossed… Putting the Bean Souffle in the oven’);

 let success = randomSuccess();

 if(success){

  return 'Bean Souffle';

 } else {

 throw 'Dinner is ruined!';
 }

};

Hey, did you figure it out? I’m just trying to understand that, but I have the same thoughts as you

What exactly is await doing when the promise gets rejected? Is it throwing the rejection reason as an error, and thats why we use a try, catch block?

Try to rewrite code

async function hostDinnerParty() {
  try {
    let resultOfCooking = await cookBeanSouffle();
    console.log(`${resultOfCooking} is served!`);
  } catch(e) {
    console.log(e);
    console.log('Ordering a pizza!');
  }
}

AS

async function hostDinnerParty() {
    let resultOfCooking = await cookBeanSouffle();
    console.log(`${resultOfCooking} is served!`);
}

When we “fail”. called reject in the Promise and don’t have appopriate handler we get

triggerUncaughtException(err, true /* fromPromise */);
            ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not handled with .catch(). 
The promise rejected with the reason "Dinner is ruined!".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

We know that " await is an operator: it returns the resolved!!! value of a promise". If the Promise is rejected, the await expression throws the rejected value. When we get rejected value of promise and don’t have handler for that rejection we get error ‘ERR_UNHANDLED_REJECTION’.

You can use a catch block or .catch() handler with callback function inside in it.

Just a small suggestion to the course team: maybe the code checker could accept console.error as well as console.log
:slight_smile: