Background assumptions:
You have a lot of configuration information stored on the server, because the configuration too much, do not want to each time all the configuration information written to the front, hoping to use the time to get the better.
Because JavaScript is single-threaded, you don't want to clog up UI rendering so you specifically wrote an asynchronous get function (Ajax gets background information)
var getconfig=function (Key,callback) {
$.get ('/config/' +key,function (config) {
Callback (Null,config);
}, ' json ');
};
Use this function
GetConfig (1,function (err,config) {
if (err) {
return Console.log (ERR);
}
Console.log (config);
});
So you can use it happily.
You find that there are many places in your JavaScript that call it, each time you launch a request that takes too much time and resources, so you're going to cache it (to illustrate the problem, we don't need a higher-order function:)).
varGetConfig = (function () { var_configs = {};//Cache Container return function(Key, callback) {if(_configs[key] = = =undefined) {$.get ('/config/' + key,function(config) {_configs[key]=config; Callback (NULL, config); }, ' JSON '); } Else { returnCallbackNULL, _configs[key]); } };}) ();
So you can happily use the configuration, the acquired configuration will be cached.
The problem is here, you run the following code
GetConfig (' db ',function(err,config) { console.log (config); // Output 2 }); Console.log (' Hello World '); // Output 1
Before we add the cache version, each time we run the code is output 1, then output 2. But after we add the cache, if the cache exists, our output turns out to be output 2 and then output 1, which may seem to have little effect in our case, but there will be some strange bugs left in some scenarios.
The problem here is an asynchronous inconsistency problem that can be solved by this problem.
varGetConfig = (function () { var_configs = {};//Cache Container return function(Key, callback) {if(_configs[key] = = =undefined) {$.get ('/config/' + key,function(config) {_configs[key]=config; returnCallbackNULL, config); }, ' JSON '); } Else{setTimeout (function(){//Change of place returnCallbackNULL, _configs[key]); },0); } };}) ();
We need to put callback's run into the next tick to run, and the asynchronous nature of the GetConfig function has been maintained.
Conclusion: When encapsulating a function, if it is an asynchronous function, you need to ensure that the callback of the function is always asynchronous. (Here is a beginner (like me) common small problem, but develop a good habit, help to ensure the robustness of the code)
Asynchronous function encapsulation Make sure that async (JavaScript needs to develop a good habit)