1. Synchronous Execution
Example :
JAVASCRIPT
The code executes line by line. This behavior is called synchronous behavior, in JS alert works synchronously.
2. Asynchronous Execution
Example 1:
JAVASCRIPT
In the above example, the second statement won’t wait until the first statement execution. In JS,
fetch()
works asynchronously.3. JS Promises
Promise is a way to handle Asynchronous operations.
A promise is an object that represents a result of operation that will be returned at some point in the future.
Example :
JAVASCRIPT
Note
A promise will be in any one of the three states:
- Pending : Neither fulfilled nor rejected
- Fulfilled : Operation completed successfully
- Rejected : Operation failed
3.1 Resolved State
When a Promise object is Resolved, the result is a value.
JAVASCRIPT
3.2 Rejected State
Fetching a resource can be failed for various reasons like:
- URL is spelled incorrectly
- Server is taking too long to respond
- Network failure error, etc.
JAVASCRIPT
3.3 Promise Chaining
Combining multiple
.then()
s or .catch()
s to a single promise is called promise chaining.Syntax :
3.3.1 OnSuccess Callback returns Promise
Here, log the response in JSON format.
JAVASCRIPT
3.3.2 Chaining OnSuccess Callback again
JAVASCRIPT
3.4 Fetch with Error Handling
Check the behavior of code with valid and invalid URLs.