> front-end

Async await

Created by: Kitman Yiu

Updated at: 1 day ago

  • Definition: Composition in programming refers to combining two or more functions to create a new function.
  • Benefits: Modularity, Readability, Maintainability, Testability
  • Examples: const multiplyByTwoAndAddThree = (x) => addThree(multiplyByTwo(x));

1. Where Does It Come From?

Origin: async/await is a programming paradigm first introduced in C# and .NET, later adopted by JavaScript and other languages. It was created to simplify asynchronous programming, making asynchronous code easier to write and read.

State Change: Before async/await, asynchronous programming relied on callbacks and events, leading to "callback hell". With async/await, asynchronous code structure became clearer and more synchronous in style.

2. What Is It?

Definition: async/await allows developers to write asynchronous code in a more synchronous manner. The async keyword declares a function as asynchronous, while await waits for an asynchronous operation to complete.

Three Key Principles:

  • Asynchronous Function Declaration: Functions declared with async return a Promise.
  • Awaiting Promise Resolution: await is used inside async functions to wait for Promise resolution.
  • Error Handling: Use try/catch to handle errors in asynchronous operations.

Practical Example:

Background: Fetching data from the internet, an asynchronous operation.

Solution: Use async/await in a function to await data fetching completion.

            
async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Fetching data failed', error);
    }
}
            
        

3. Where Is It Going?

Limitations: async/await applies only to Promise-based operations and not suitable for non-Promise async operations.

Optimization Direction: The industry is exploring better error handling and integration of asynchronous flow control tools, like functional programming with async/await.

Future Development: Potential for more language features and tools to simplify asynchronous programming, improving concurrent processing and integration into various programming environments.