I have to write a javaScript function that return some data to the caller.
In that function I have multiple ways to retrieve data i.e.,
The problem in your example getOrder
lies in that if the 3 lookup functions are going to be asynchronous, you won't get the order back from them right away and as they are not blocking, the getOrder
would return null
; You would be better off defining a callback function which takes action on the first returned order
data and simply ignores the rest of them.
var doSomethingWithTheOrder = function CallBackOnce (yourResult) {
if (!CallBackOnce.returned) {
CallBackOnce.returned = true;
// Handle the returned data
console.log('handle', yourResult);
} else {
// Ignore the rest
console.log('you are too late');
}
}
Make your data lookup functions accept a callback
function cacheLookUp(id, callback) {
// Make a real lookup here
setTimeout(function () {
callback('order data from cache');
}, 3000);
}
function localeStorageLookUp(id, callback) {
// Make a real lookup here
setTimeout(function () {
callback('order data from locale storage');
}, 1500);
}
function restLookUp(id, callback) {
// Make a real lookup here
setTimeout(function () {
callback('order data from rest');
}, 5000);
}
And pass the callback function to each of them
function getOrder(id) {
cacheLookUp(id, doSomethingWithTheOrder);
localeStorageLookUp(id, doSomethingWithTheOrder);
restLookUp(id, doSomethingWithTheOrder);
}