वेब और ऐप डेवलपमेंट की दुनिया में डेटा लाना (फैचिंग data) एक बहुत आम काम है — जैसे किसी API से यूज़र की जानकारी, मौसम का डेटा या प्रोडक्ट लिस्ट लाना।
इसी काम को करने के लिए JavaScript हमें एक बहुत ही आसान और मॉडर्न तरीका देती है
fetch() क्या है?
fetch() एक built-in JavaScript function है जो किसी URL से डेटा लाने के लिए इस्तेमाल की जाती है।
यह function Promise रिटर्न करता है, जिससे आप डेटा मिलने तक “wait” कर सकते हैं, बिना प्रोजेक्ट में बाकी कोड को रोके।
Basic Example:
fetch('https://api.example.com/users')
.then(response => response.json()) // response को JSON में बदलें
.then(data => console.log(data)) // डेटा को console में दिखाएं
.catch(error => console.error('Error:', error)); // अगर error आए
यहाँ क्या हुआ?
fetch() को API का URL दिया गया।
यह एक Promise रिटर्न करता है — यानी "डेटा आने वाला है"।
जब डेटा आ जाता है, तो हम .then() का इस्तेमाल करके उसे संभालते हैं।
अगर कुछ गलत होता है, तो .catch() से error पकड़ सकते हैं।
Promises क्या हैं?
Promise JavaScript का ऐसा ऑब्जेक्ट है जो किसी asynchronous काम (जैसे API call, file पढ़ना, आदि) का future result represent करता है।b
Promise के तीन possible states होते हैं
Pending – काम अभी चल रहा है
Resolved / Fulfilled – काम सफल रहा
Rejected – काम असफल रहा
Example:
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("सफल हुआ!");
} else {
reject("कुछ गलती हो गई!");
}
});
myPromise
.then(message => console.log(message))
.catch(error => console.error(error));
👉 Output:
सफल हुआ
async और await के साथ fetch()
then() और catch() से भी आसान तरीका है — async/await।
यह कोड को synchronous जैसा दिखाता है, जिससे readability बढ़ती है।
async function getUsers() {
try {
let response = await fetch('https://api.example.com/users');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getUsers():
Error handling try...catch से साफ़
Modern JavaScript का best practice
fetch() JavaScript का modern तरीका है किसी API से डेटा लाने का।
यह Promises पर आधारित है, जिससे asynchronous काम को handle करना आसान हो जाता है।
async/await syntax से कोड और भी readable और clean बन जाता है ।