Asynchronous function encapsulation Make sure that async (JavaScript needs to develop a good habit)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.