Mastering the Promise Pattern in JavaScript: Clean Async Code Made Easy
This article explains the Promise pattern in JavaScript, showing why nested Ajax callbacks hurt readability and user experience, how Promise improves flow with three states, and demonstrates practical usage with a lightweight promise.js library and jQuery Deferred examples.
What is the Promise pattern
In scenario A makes an Ajax request and in its callback calls B, which also makes an Ajax request. This nested callback style leads to poor readability and bad user experience because each request blocks the next step.
Using new Promise(A).done(B); expresses that B should run after A completes, allowing the rest of the code to continue executing while A is pending.
Promise is part of the CommonJS specification and helps control code flow, avoiding deep nesting. It enables non‑blocking, asynchronous logic without passing callbacks directly.
Promise has three states:
unfulfilled (pending)
resolved (fulfilled successfully)
rejected (failed)
How to use the Promise pattern
(1) promise.js
promise.js is a lightweight 2 KB implementation of the Promise pattern. It is simple to use.
(2) jQuery Deferred
jQuery 1.5 introduced Deferred, which follows the Promise pattern. Deferred rewrites the Ajax module, allowing concise asynchronous calls:
$.ajax("/test")
.done(function(){ alert("ok"); })
.fail(function(){ alert("err"); });Deferred also permits adding multiple callbacks that execute in the order they were added:
$.ajax("/test")
.done(function(){ alert("ok"); })
.fail(function(){ alert("err"); })
.done(function(){ alert("ok 2"); });Ajax already uses Deferred internally; when not using Ajax you can create your own Deferred object.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
