Awaiting


These blogs are getting more and more difficult to write. What does one write about and still sound interesting? I don’t know. But here we go, I guess.

I did have a pretty big personal breakthrough this week, though it didn’t come while working on my capstone project. While working on my Intermediate API assignment for Cloud Development, I finally figured out how to turn a .then() chain into an ‘async’ function using ‘await.’ When I say “figured out,” what I mean is I actually understand what is going on. So, a normal .then() chain might look like this:

app.get('/', (req, res) => {
    get_some_data_from_database()
        .then( (data) => res.render(data) )
        .catch( (err) => console.log(err) );
    }
);

While this looks alright when laid out like this, I find it very easy to make it look gross and confusing. I think this is also good if one is working truly asynchronously, but don’t quote me on that. I believe that is because the process won’t block while the get_some_data_from_database() function is working then “then” performs the callback function in the .then() chain.

In constrast:

app.get('/', async (req, res) => {
    try {
        const data = await get_some_data_from_database();
        res.render(data);
    } catch (err) {
        console.log(err)
    };
});

To me, this seems a lot cleaner. We have the try/catch block to catch errors with the Promise from the get_some_data_from_database() function. This will call that function, then wait until the Promise is resolved and render the data. Alternatively, in this case, we could drop the await function call straight into the render call. I like to start with the variable approach because I’ll often want to do some processing on the data before rendering it.

This felt like a pretty big breakthrough to me because I was never explicitly taught this concept and never really understood it from other explanations. It just clicked one day while I was working through things.

Anyway, that’s really all I have. The work continues. We are almost finished with the front-end layouts and are slowly moving to connect our back-end database API to it. Exciting times.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *