Deferred States
In this page:
var dfd = $.Deferred(); // state: "pending"
dfd.resolve(value); // state: "resolved" -> done() runs
dfd.reject(reason); // state: "rejected" -> fail() runs
dfd.state(); // read the current state
Pending State
हर नया Deferred pending state में शुरू होता है, यानी इसका underlying task अभी किसी भी direction में खत्म नहीं हुआ है। Pending हमेशा शुरुआती state होती है।
उदाहरण: Pending State
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const dfd = $.Deferred();
console.log(dfd.state());
</script>
</body>
</html>
Resolved State
जब किसी Deferred पर resolve() call किया जाता है, यह resolved state में चला जाता है, और उससे attached कोई भी done() callbacks उसे pass की गई values के साथ तुरंत call हो जाते हैं।
उदाहरण: Resolved State
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const dfd = $.Deferred();
dfd.done(function(value) { console.log(value); });
dfd.resolve("done!");
</script>
</body>
</html>
Rejected State
जब किसी Deferred पर reject() call किया जाता है, यह rejected state में चला जाता है, और उससे attached कोई भी fail() callbacks reject() को pass की गई values के साथ call हो जाते हैं।
उदाहरण: Rejected State
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const dfd = $.Deferred();
dfd.fail(function(reason) { console.log(reason); });
dfd.reject("something failed");
</script>
</body>
</html>
State वापस नहीं जा सकती
एक बार कोई Deferred resolve या reject हो जाए, इसकी state वापस pending में नहीं जा सकती या दूसरे outcome में switch नहीं हो सकती — final state permanent है।
उदाहरण: State Cannot Go Back
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const dfd = $.Deferred();
dfd.resolve();
console.log(dfd.state());
dfd.reject();
// has no effect, already resolved
</script>
</body>
</html>
किसी Task में State Check करना
state() method current state को एक string (pending, resolved, या rejected) के रूप में return करता है, जो तब उपयोगी है जब आपको check करना हो कि कोई async।
उदाहरण: Check State in a Task
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const dfd = $.Deferred();
if (dfd.state() === "pending") {
console.log("Still working");
}
</script>
</body>
</html>
- किसी Deferred की state settle हो जाने के बाद उसे बदलने की कोशिश करना, जैसे
resolve()के बादreject()call करना, जबकि state final है और दूसरी call ignore हो जाती है। - async work शुरू करने के तुरंत बाद
dfd.state()check करना और"resolved"की उम्मीद करना, जबकि यह अभी भी"pending"है। "rejected"को code में throw हुए किसी error से confuse करना, जबकि इसका मतलब सिर्फ यह है किreject()call किया गया था।
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: