DEV Community


Promises in javascript

henryfradley profile image Henry Fradley ・1 min read

Promises in javascript are a lot like promises in real life. A promise can either be unresolved, resolved, or rejected. Imagine an example where when you were a child your mom made you promise that you would make you clean your room after school. That promise would be pending(unresolved) while you were still in school, the promise would be resolved if you made your bed when you got home, or it would be rejected if your mom came home from work and you still hadn't made your bed.

In javascript a promise is pending if the result is not yet ready, usually it is waiting on a server to send some data or a function to finish, a promise is resolved when the result is available and the promise received the expected output, and a promise is rejected on an error.

Promises really become helpful when working with asynchronous code. Javascript by its nature is synchronous meaning it can only execute one line of code at a time. This is troublesome because one line of code that is taking a long time to complete will completely halt the entire process of running the rest of the code.
This is where promises come in. By using a promise on a portion of code that may take an unknown amount of time javascript will keep running the rest of the code and only go back and run the promise when that function is completed. This is especially helpful for retrieving data from servers or loading images or other large files.

Discussion (0)

Editor guide