

The analogy isn’t terribly accurate, because JavaScript promises are more complex than a simple subscription list: they have additional features and limitations. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready. In terms of our analogy: this is the “subscription list”. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together.A few logs show how the synchronous part of the method is. The fulfillment of the promise is logged, via a fulfill callback set using p1.then(). The Promise() constructor is used to create the promise. A “consuming code” that wants the result of the “producing code” once it’s ready. It creates a promise that will be fulfilled, using setTimeout(), to the promise count (number starting from 1) every 1-3 seconds, at random.For instance, some code that loads the data over a network. A “producing code” that does something and takes time.This is a real-life analogy for things we often have in programming: And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified.Įveryone is happy: you, because the people don’t crowd you anymore, and fans, because they won’t miss the song. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. To get some relief, you promise to send it to them when it’s published. Imagine that you’re a top singer, and fans ask day and night for your upcoming song.
