Skip to main content

Command Palette

Search for a command to run...

Async/await, Promises and Pure Functions

Updated
β€’3 min read
Async/await, Promises and Pure Functions
O

I'm a community-minded engineer based in Berlin, originally from Romania, and I grew up in sunny Spain. I combine the best of both communication and technical skills, with experience in both the engineering world and the business side of things. I'm proficient in a wide range of technologies like JavaScript, React.js, Redux, TypeScript, Node.js, HTML/CSS, Styled Components, SASS, and REST APIs. I love going beyond just writing code by sharing knowledge with my team through Communities of Practice (COPs), Employee Resource Groups (ERGs), and detailed technical documentation. My main interests are in frontend frameworks, web standards, accessibility (A11y), and Clean Code. My passion for programming started in high school when I built my first website. Since 2019, I've been working as a professional software developer, thriving in agile and iterative environments. Nearly five years later, I'm still excited to dive into code and collaborate with my colleagues. I'm very open and friendly, good at turning technical concepts into easy-to-understand information for everyone.

⏳ JavaScript: Async, Promises & More

πŸ€” Is JavaScript Synchronous?

Yes – JavaScript is a synchronous, single-threaded language. It runs one thing at a time, line by line.

But... we can mimic asynchronous behaviour using:

  • Callbacks

  • Promises

  • Async/Await

These tools allow us to:

  • Wait for data (like from APIs)

  • Handle delays (like timers)

  • Avoid blocking the main thread

πŸͺ Callbacks

A callback is a function passed into another function to be run later.

function fetchData(callback) {
    setTimeout(() => {
        callback('data received!');
    },1000)
}

fetchData((result) => {
    console.log(result);
});

🧠 But callbacks can get messy – known as "callback hell":

doThing(() => {
    doNext(() => {
        doAnother(() =>{
            // ...
        })
    })
})

πŸ’­ Promises

A promise is a JavaScript object that represents a value you don't have yet, but will get in the future (or maybe not).

It's like saying "I promise you something later".

🧱 A promise has 3 possible states:

  • Pending – still waiting

  • Fulfilled – got the value

  • Rejected – something went wrong

You can use .then() for success and .catch() for errors:

fetchData()
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

⚑ Async / Await

  • Syntactic sugar over promises πŸš€

  • βœ… Makes async code look synchronous

  • πŸ“¦ await can only be used inside an async function

async function getData() {
    try {
        const res = await fetchData();
        console.log(res);
    } catch (err) {
        console.log(err);
    }
}

What Does Async Functions Return and Why?

βš™οΈ async/await is syntax sugar for promises. When you write async in front of a function, it wraps that code in a promise and returns a promise that will resolve with the return of that function.

🧠 So whenever you have an async function, that function will return a promise that ends up resolving with whatever the return value is.

Example:

import { useEffect, useState } from "react";

function Characters() {
    const [people, setPeople] = useState([]);

    async function getPeople() {
        try {
            const data = await fetch("https://swapi.dev/api/people");
            const response = await data.json();
            setPeople(response.results);
        } catch (err) {
            console.log(err.message);
        }
    }

    useEffect(() => {
        getPeople();
    }, []);

    return (
        <>
            {people.map((character, index) => (
                <p key={index}>{character.name}</p>
            ))}
        </>
    );
}

export default Characters;

What Is a Pure Function and When Do We Use It?

A pure function is very useful when using functional programming. Why? Because it does not modify anything else - it has no side effects. 🌱

You just give it an input and it gives you an output, without changing:

  • Any global state of the system 🌐

  • Or any external dependencies (like APIs, localStorage, DBs)

βœ… This is extremely good because they are very deterministic - given the same input, you always get the same output.

Pure functions are commonly used in functional programming and in most JavaScript codebases. They make things simpler, more predictable, and easier to test.