Skip to content

Instantly share code, notes, and snippets.

@Acesmndr
Created January 6, 2018 08:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Acesmndr/a34823d629b5bf3311eb69217df62046 to your computer and use it in GitHub Desktop.
Save Acesmndr/a34823d629b5bf3311eb69217df62046 to your computer and use it in GitHub Desktop.
AJAX with callbacks and promises
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; // importing xmlhttprequest package because node doesn't support it out of the box
const superHeroes = ['Batman', 'Superman', 'WonderWoman', 'Flash', 'Cyborg', 'Aquaman', 'Green Lantern', 'Martian Manhunter']; // an array of request params
const completedFetchingData = () => { // function to be called when all ajax requests complete.
console.log('Just completed fetching the data');
}
const failedFetchingData = () => { // function to be called when data fetching fails
console.log('Failed to fetch the data');
}
const ajaxRequestWithPromise = (param) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => { // a listener which executes when the xhr request succeeds
resolve(JSON.parse(xhr.responseText));
});
xhr.addEventListener('error', () => { // a listener which executes when the xhr request fails
reject(new Error(xhr.statusText));
})
xhr.open('GET', `https://httpbin.org/get?param=${param}`);
xhr.send();
});
}
const request = async () => { // async function always returns a promise
for(let i = 0; i < superHeroes.length; i++) {
const response = await ajaxRequestWithPromise(superHeroes[i]); // await can be only used inside async functions
console.log(response.args);
}
completedFetchingData();
}
request().catch((error) => { failedFetchingData(); }); // catch rejected promise
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; // importing xmlhttprequest package because node doesn't support it out of the box
const superHeroes = ['Batman', 'Superman', 'WonderWoman', 'Flash', 'Cyborg', 'Aquaman', 'Green Lantern', 'Martian Manhunter']; // an array of request params
const completedFetchingData = () => { // function to be called when all ajax requests complete.
console.log('Just completed fetching the data');
}
const ajaxRequest = (param, callback) => { // a simple vanilla ajax request with callback
let xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => { // a listener which executes when the xhr request succeeds
callback(JSON.parse(xhr.responseText));
});
xhr.open('GET', `https://httpbin.org/get?param=${param}`);
xhr.send();
}
superHeroes.forEach((superHero, index) => {
ajaxRequest(superHero, (response) => {
console.log('Response', response.args);
if (index === superHeroes.length - 1) { // executes only when the callback is of the last superhero
completedFetchingData();
}
});
});
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; // importing xmlhttprequest package because node doesn't support it out of the box
const superHeroes = ['Batman', 'Superman', 'WonderWoman', 'Flash', 'Cyborg', 'Aquaman', 'Green Lantern', 'Martian Manhunter']; // an array of request params
const completedFetchingData = () => { // function to be called when all ajax requests complete.
console.log('Just completed fetching the data');
}
const failedFetchingData = () => { // function to be called when data fetching fails
console.log('Failed to fetch the data');
}
const ajaxRequest = (param, callback) => {
let xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => { // a listener which executes when the xhr request succeeds
callback(JSON.parse(xhr.responseText));
});
xhr.addEventListener('error', () => { // a listener which executes when the xhr request fails
callback({ error: xhr.statusText });
})
xhr.open('GET', `https://httpbin.org/get?param=${param}`);
xhr.send();
}
let superPromises = []; // an array to hold promises of ajax request for all superHeroes.
superHeroes.forEach((superHero) => {
superPromises.push(new Promise((resolve, reject) => {
ajaxRequest(superHero, (response) => {
if (!response.error) { // if response is not error
console.log(response.args);
resolve();
} else {
reject();
}
});
}));
});
Promise.all(superPromises).then(() => { // execute when all promises are fulfilled
completedFetchingData();
}, () => {
failedFetchingData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment