जावास्क्रिप्ट में प्रॉमिस चेन
मान लीजिए हमारे पास निम्नलिखित प्रॉमिस है:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('string');
}, 3000);
});
प्रॉमिस के पूरा होने पर इसके परिणाम को कंसोल में प्रिंट करते हैं:
promise.then(
function(result) {
console.log(result); // 'string' प्रिंट करेगा
}
)
आइए अब परिणाम को तुरंत प्रिंट न करें,
बल्कि इसे किसी तरह बदलें और return के माध्यम से वापस करें:
promise.then(
function(result) {
return result + '!';
}
);
इस स्थिति में, हम अपने then के परिणाम पर
एक और then लागू कर सकते हैं, जिससे
श्रृंखला बनती है। इसके साथ ही
अगले मेथड के परिणाम में वह चला जाएगा
जो पिछले मेथड ने return के माध्यम से वापस किया था:
promise.then(
function(result) {
return result + '!';
}
).then(
function(result) {
console.log(result); // 'string!' प्रिंट करेगा
}
);
इस प्रकार कितनी भी लंबी श्रृंखला बनाई जा सकती है:
promise.then(
function(result) {
return result + '1';
}
).then(
function(result) {
return result + '2';
}
).then(
function(result) {
return result + '3';
}
).then(
function(result) {
console.log(result); // 'string123' प्रिंट करेगा
}
);