Promises and Async/Await Explained

One of the most difficult concepts that you will encounter in programming is dealing with asynchronous operations. Asynchronous code management in Javascript is important since it helps the applications in such tasks like pulling data from the server, reading files, performing operations which require time. Javascript language facilitates this with the help of promises and use of the async await syntax.

We will provide an overview of these two terms,ones that you will often hear in JavaScript, promises and async/await and discuss their contribution to a better way of writing JavaScript.

What are Promises?

In the programming universe, it is often said that Javascript is the only true asynchronous programming language, this is due to the fact that Javascript contains a myriad of functionality and components that allow for deeper use tailoring such as TIMEOUTS. A promise is one of those components or components that allow an asynchronous request to be made from one component to another, javascript is built around the concept of promises whether you realize it or not it's blended within out the language the same way as Proxies are.

Javascript promises could be said as a Javascript object which aids in the commanding and controlling of other objects, whether they encourage progress or result in failure, depending on how you see them. The concepts behind Javascript promises are China based, using them is simple, generally two command code loops are constructed to issue commands, based on the objects attributes and the output one loop becomes primary enabling the two to speak and the message being sent rounds. This feature is monumental for building and enhancing further functionality down the line enabling far smoother dealing.

When working with asynchronous requests, for instance this could range from network requests to simple database calls, you wouldn't expect it to be instantaneous, hence functional codes are constructed to enable other operations to be carried out while the primary requests are outstanding, bands around the primary request will block secondary loops once that primary request output is recognized , allowing for clean and efficient coding without the use of excessive nested loops.

In computing, the outcome of a promise falls in one of the three categories:

1. Pending : A promise that is issued for the first time will be in the "pending" stage. An operation is still underway.

2. Fulfilled : A promise that has been successfully resolved. A result has been achieved and the operation is completed.

3. Rejected : A promise that has not reached its success is marked as rejected. It can also mean an error or failure was the cause.

The following syntax is used to create a promise: `new Promise()`. This syntax has a function called the executor, which encases the asynchronous task. The two parameters accepted by the executor function are `resolve` and `reject`. When `resolve` is invoked, the task was concluded successfully. However, if it fails, then the `reject` function initiates, indicating that the task has failed.

Here is the basic structure of a promise,

Promise Structure

  let promise = new Promise(function(resolve, reject){
// Asynchronous operation
let success = false;
// A piece of code that determines if a success or failure simulation will be fired
if(success) {
resolve("Operation was successful"); // The promise is fulfilled
} else {
reject("Operation failed"); // The promise is rejected
}
});

promise
.then(function(result) {
console.log(result); // If resolved, show the success message.
}).catch(function(error) {
console.log(error); // If rejected, show the error message.
});
After completing the creation of the promise, you may, however, use the ".then ()" method to add functions to the piecing that you will carry out in the event in case the promise is satisfied. Utilizing the ".catch ()" function aids in solving complications that arise whenever the promise is unsatisfied.


How To Chain Promises

As observed, chaining multiple promises one after the other is made possible by the powerful Promises. Multiple asynchronous operations can be chained using `.then`. The successive asynchronous operations are invoked in the order in which they are supposed to be executed.

Here's an example of how chaining works:

Promise Chaining Example

  fetchDataFromAPI().then(function(response) {
return processData(response); // Returning new promise
})
.then(function(processedData) {
return saveData(processedData); // Returning another promise
})
.catch(function(error) {
console.log("Error: " + error);
});
In the above example, clearly we can see every other `then` block starts off with a new promise and whichever `then` block comes later can only be executed if the promise preceding it is completed. .Finally, Penny's shoes can only be ordered if – any of the promises in the chain are undone and fail the test, chain-fail bubble-matches shoes undying phones the success of an otherwise percent.

What is Async/Await?

As far as hybridizing the ways of handling asynchronous tasks is concerned, `async` and `await` in JavaScript go a step further, as they extend Pseudo Code, using pseudo logic and utilizing multiple tasks in order to expand for better overall performance of code.

- Function 'async' : An 'async' function can be defined as that function which always results in a promise being returned. The definition of the 'async' keyword is also found before the function containing the definition, meaning that a function has the capacity to perform asynchronous operations directly.

- Await : 'Async' functions contain the 'await' keyword which is used to suspend the function's execution until the task is complete.

As a result of using 'await', one mustn't have to perform all the finicky handling of an unwrapped promise thanks to all the unhandled rejection mess. The biggest drawback of using Promises is their over complication. Instead of having multiple nested callback functions, which may be avoided when there is a promise, the use of 'try...catch' is essential every time a promise is created.

Below is a clear example illustrating the combined usage of `async` and `await` keywords at the same time:

Async/Await Example

  async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
return data;
}

fetchData().then(function(result){
console.log(result);
}).catch(function(error){
console.log("Error: " + error);
});
In this example, the `await` keyword defers the execution of the `fetchData()` function until the promised `fetch` call is completed and only then resumes the next line which is a `response.json()` call. Overall, controlling logic flow for asynchronous code is made a lot easier when using async/await compared to plain promises.

Async/Await for Error Handling

Another day you sit down to write code in JavaScript and you know you have to deal with errors. Errors are part of the reliable code and are crucial aspects that need management. Errors when using promises can be handled by the `.catch()` method. Answering the question `how async/await works`, promise errors using the `async/await` syntax you have to use `try...catch` blocks and it will be handled like normal synchronous code.

Related Articles