Home > Blockchain >  When would you want to create your own JavaScript Promise?
When would you want to create your own JavaScript Promise?

Time:05-23

I am new to JavaScript and learning about Promises. I am having some trouble figuring out when you would want to create your own Promise. Initially I was under the impression that the "executor function" (the function you pass into the Promise constructor) was handled asynchronously by the browser API (if your JavaScript is running in a browser). With that understanding you could then, for example, use your created Promise to perform some long-running calculation asynchronously in the background.

However, I learned that the executor function is actually executed synchronously as soon as the Promise is created (thus blocking the main thread of execution if you have a some long running code in that executor function). So now I'm wondering in what cases would you want to define your own Promises. My understanding is that a lot of the asynchronous functions like fetch for example already return promises - and thus it would be redundant to wrap those functions in a promise.

Can someone give me an example of when you would want to create your own Promise? Sorry if this is a silly question or if my understanding is off, still learning.

Thanks in advance!

CodePudding user response:

My understanding is that a lot of the asynchronous functions like fetch for example already return promises

Actually, most don't. setTimeout, addEventListener, etc - they all take a callback and need to be promisified when you want to use a promise.

The trend to native functions that already return promises is still a recent occurrence, only new APIs like fetch do this. For libraries, the picture is similar - modern libraries will provide promises, but old ones are still around.

Apart from that, you're right - you rarely need new Promise, in normal code all you'll do is promise chaining (or even just use async/await). However, new Promise is still the primitive building block that underlies all these abstractions, and it won't go away.

  • Related