await/async Why the 2 pieces of code doesn't run the same?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
When writing asynchronous code in JavaScript, understanding the `async` and `await` keywords is crucial. These features simplify the process of working with promises, making code easier to read and manage. However, misconceptions about their use can lead to unexpected behavior, especially when comparing code snippets that don't produce the same outcome despite appearing similar. This article explores why `async`/`await` structures can result in different execution patterns and includes a detailed breakdown to help you grasp the core concepts.
Understanding `async` and `await`
What is `async`?
The `async` keyword is used in front of a function declaration or expression to define an asynchronous function. An `async` function is one that potentially contains asynchronous operations. When called, it returns a promise automatically, even if you do not explicitly return a promise inside the function.
What is `await`?
The `await` keyword can only be used inside `async` functions. It pauses the execution of the function until the promise it is waiting for settles. It essentially unwraps the value of the promise after it resolves, allowing you to work with the value directly, as if the asynchronous code was synchronous.
Key Differences in Code Execution
Let's explore two code snippets that don't behave the same, although they might seem to at first glance.
Snippet 1
- Function Definition:
- In Snippet 1, `fetchData` is an `async` function, automatically returning a promise.
- In Snippet 2, `fetchData` is a regular function that uses promise chaining with `.then()`.
- Handling Asynchronous Operations:
- Await Mechanism: In Snippet 1, `await` ensures the execution of `fetchData` pauses until `getDataFromApi()` resolves. This does not happen in Snippet 2.
- Promise Handling: Snippet 2 is more explicit in handling the promise returned by `getDataFromApi()`, as it directly chains to handle results.
- Error Handling:
- Inside `async` Functions: Snippet 1 can neatly handle errors with `try-catch`, making the code cleaner.
- Promise Chaining: Snippet 2 requires `.catch()` to handle any potential errors.
Related reading
- Awaiting multiple Tasks with different results
- AWS ECS Fargate and multi threading
- AWS Lambda - If I Start a Thread, what Happens when the Lambda is Frozen/Thawed?
- AWS lambda and Java concurrency
- AWS Amplify, how to check if user is logged in?
- AWS Javascript SDK v3 - Typescript doesn't compile due to error TS2304 Cannot find name 'ReadableStream
- AWS Lambda async code execution
- AWS ruby sdk for Async non blocking calls
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.