I have a web page where different parts of it all need the same back-end data. Each is isolated, so they each end up eventually making the same calls to the back-end.
What is the best way to avoid making a call to the web server when one is already in progress and initiated by a different piece of code on the same web page?
Here's an example. I'll use setTimeout to simulate an asynchronous call.
Let's assume there's an async function that returns the list of contacts, which is basically a simple array of strings in this example:
var getContacts = function() {
log('Calling back-end to get contact list.');
return new Promise(function(resolve, reject) {
setTimeout(function() {
log('New data received from back-end.');
resolve(["Mary","Frank","Klaus"]);
}, 3000);
});
};
Now, let's create three separate functions that each call the above function for different purposes.
Dump out the list of contacts:
var dumpContacts = function() {
getContacts().then(function(contacts) {
for( var i = 0; i < contacts.length; i++ ) {
log( "Contact " + (i + 1) + ": " + contacts[i] );
}
});
};
Determine if a particular contact is in the list:
var contactExists = function(contactName) {
return getContacts().then(function(contacts) {
return contacts.indexOf(contactName) >= 0 ? true : false;
});
};
Get the name of the first contact:
var getFirstContact = function() {
return getContacts().then(function(contacts) {
if ( contacts.length > 0 ) {
return contacts[0];
}
});
};
And here is some example code to use these three functions:
// Show all contacts
dumpContacts();
// Does contact 'Jane' exist?
contactExists("Jane").then(function(exists){
log("Contact 'Jane' exist: " + exists);
});
getFirstContact().then(function(firstContact){
log("first contact: " + firstContact);
});
The above routines make use of a global log() function. console.log() could be used instead. The above log() function log's to the browser window and is implemented as follows:
function log() {
var args = Array.prototype.slice.call(arguments).join(", ");
console.log(args);
var output = document.getElementById('output');
output.innerHTML += args + "<br/>";
}
and requires the following in the html:
<div id='output'><br/></div>
When the above code is run, you will see:
Calling back-end to get contact list.
and
New data received from back-end.
three times, which is unnecessary.
How can this be fixed?
This sample is on Plunker can be executed:
http://plnkr.co/edit/6ysbNTf1lSf5b7L3sJxQ?p=preview
See Question&Answers more detail:
os