This was sparked by a sudden thought.
First, let's see how MDN defines Promise.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
Think of it this way -- you participate in a lucky draw contest which offers a prize of $1000 voucher. You are given a ticket as a record.
let ticketPromise = new Promise(() => luckyDrawProcess());
You really hope that you win this lucky draw so you can buy the newest noise-cancelling headset 🎧 Else... maybe you'll just get an ice-cream to cheer yourself up 🍦
ticketPromise
.then((thousandDollarVoucher) => {
buyHeadSet(thousandDollarVoucher);
})
.catch(lostHope => buyIceCream());
Basically, a Promise is an object that promises you a result in the future. You can pre-determine your actions based on the result you get and whether it is resolved or rejected.
Promises are more than just this though, and the rest is for you to find out ;)
Top comments (0)