Promises In JavaScript: The Basics

A promise in JavaScript switches from synchronous to asynchronous JavaScript. Using this, we can continue running the rest of the code while we are doing something else. Usually you can do this with data fetching to show the information from the database later when the promise is finally finished. In this post, I will outline the basic concepts of promises in javascript.

The basics: a promise.

To understand the basics of promises in JavaScript, you must understand: a promise.

What is a promise? A promise in an object that “promises” or “may” produce a value in the future (which could fail if the operation fails to produce this). Promises are common when performing actions in Asynchronous functions. Async Await is just syntactic sugar for promises to make things much easier/simple.

Syntactical sugar in a programming language is syntax within a language that is designed to make it easier to do something. In this case, JavaScript implements Async Await to simplify the process of using promises. Promises used to be wrote out, but with the syntactical sugar, we can more easily use it.

Async Await Syntactic Sugar

An asynchronous function (which runs “alongside” other code can be marked with “async”) can look like this:

async function YourFunc() {

The keyword: “Await” is permitted within an Async function. The await keyword awaits for a promise in JavaScript to finish before running.

Use this keyword with your API calls, and you can have the code await for the fetch to complete before proceeding forward.

To do a deeper dive beyond concept, you can read MDN’s guide to promises here.

Conclusion

Asynchronous programming can help your application do more without creating a callback hell. If you haven’t heard of callback hell, checkout my post here.

Christian Van Loon spell checked this. Check out his linkedin profile here.