DEV Community

Cover image for What is a Promise in JavaScript ?
Aayush Jain
Aayush Jain

Posted on • Updated on

What is a Promise in JavaScript ?

What is a Promise?

*(in JavaScript)

A promise is an article that may ๐ŸŒŒ produce a solitary worth at some point ๐Ÿ•  later on ๐Ÿ“… with either a settled ๐Ÿ’ฏvalue or a cause ๐Ÿ’ฌ that it's not ๐Ÿ˜ resolved.*

How Promises Work

๐ˆ๐ญ ๐ฐ๐ข๐ฅ๐ฅ ๐Ÿ‘ ๐›๐ž ๐—ณ๐—ฎ๐—น๐—น๐—ถ๐—ป๐—ด ๐—จ๐—ป๐—ฑ๐—ฒ๐—ฟ ๐จ๐ง๐ž โ˜๏ธ ๐จ๐Ÿ ๐ญ๐ก๐ž ๐Ÿ‘ ๐ฉ๐จ๐ฌ๐ฌ๐ข๐›๐ฅ๐ž ๐ฌ๐ญ๐š๐ญ๐ž๐ฌ:

๐Ÿ‘‰๐๐ž๐ง๐๐ข๐ง๐ : This is an initial stage of the Promise ๐Ÿคž previously ๐Ÿค” an operation ๐Ÿ’ starts.

๐Ÿ‘‰๐…๐ฎ๐ฅ๐Ÿ๐ข๐ฅ๐ฅ๐ž๐: This state demonstrates that ๐Ÿ”€ the specified operation was finished. โœ…

๐Ÿ‘‰๐‘๐ž๐ฃ๐ž๐œ๐ญ๐ž๐: ๐Ÿšซ This state ๐Ÿ‡บ๐Ÿ‡ธ demonstrates that ๐Ÿ‘‰ the operation ๐Ÿ’ didn't finish. In ๐Ÿ˜ฉ this case, a blunder ๐Ÿšซ esteem ๐Ÿ‘‡ will be thrown๐Ÿ™€.

๐–๐ก๐ฒ ๐Ÿค”๐๐จ ๐ฒ๐จ๐ฎ ๐ง๐ž๐ž๐ ๐Ÿ˜ฌ ๐š ๐ฉ๐ซ๐จ๐ฆ๐ข๐ฌ๐ž?

Promises are utilized ๐ŸšŸ to deal with nonconcurrent activities.

They give ๐Ÿ‘‹ an another way to deal with callbacks by lessening โฌ the callback hell and composing the cleaner code๐Ÿ’ป.

๐–๐ก๐š๐ญ ๐Ÿ™Œ ๐š๐ซ๐ž ๐ญ๐ก๐ž ๐ฆ๐š๐ข๐ง ๐ซ๐ฎ๐ฅ๐ž๐ฌ ๐จ๐Ÿ ๐ฉ๐ซ๐จ๐ฆ๐ข๐ฌ๐ž?

๐Ÿคž A promise is an item that ๐Ÿœ supplies a standard-consistent .then() method

๐ŸคžA forthcoming promise might change into ๐Ÿค“ either satisfied or dismissed by the state.

๐ŸคžA satisfied or dismissed ๐Ÿšซ promise ๐Ÿคž is settled and it should not โš™๏ธ change into ๐Ÿ‘‰ any ๐Ÿ•บ other state.

๐Ÿ‘†Once a promise ๐Ÿคž is settled, the worth ๐Ÿ’ต should not โœ–๏ธ change.

Promise Chaining

Since .then() consistently returns another promise, it's feasible to chain promises with exact power over how and where blunders are taken care of. Promises permit you to imitate typical simultaneous code's attempt/get conduct.

What is the contrast among Callbacks and Promises?

A callback function is a function passed into ๐ŸšŸ๐Ÿ‘‰ one more function as a contention.

This capacity is conjured inside ๐Ÿ’  the external function to finish an activity. ๐ŸŽฌ

The principle Difference between Callback-functions and Promises is that we Attach a Callback-function to a Promise instead of passing it.

So we actually use callback functions with Promises, yet in an unexpected way (chaining).


Hope you found it useful...

Discussion (0)