Minute lets you solve, the asynchronous load causes the abnormal data

Time:2021-3-3

async-demo

On some methods of handling asynchronous requests

1. Common JavaScript scenarios

  • 1.setInterval setTimeoutThis timer function.

  • 2. HTTP requestvue-resourcefetchaxios. And so on.

2. Common phenomena

  • 1. Can’t get the results as required

  • 2. To get the result, we need to use the traditional callback function, which is very cumbersome.

function A(){
       setTimeout(B(),200);
        C();
 
}
A()
Execution sequence a - > b - > C

var c="";
Vue.http.jsonp('http://ipinfo.io/json').then(function(data) {
    self.weatherData.city = data.data.city;
    self.weatherData.country = data.data.country;
    c= data.data.city;
    });
c=?

3. Main methods

  • 1. Callback function

f1();
f2();

function f1(callback){
    setTimeout(function () {
      //Task code of F1
      callback();
    }, 1000);
  }

f1(f2);
  • 2. Event monitoring

f1.on('done', f2);
function f1(){
    setTimeout(function () {
      //Task code of F1
      f1.trigger('done');
    }, 1000);
 }
f1();
  • 3. Publish / subscribe

jQuery.subscribe("done", f2);
function f1(){
    setTimeout(function () {
      //Task code of F1
      jQuery.publish("done");
    }, 1000);
}
f1();
jQuery.unsubscribe("done", f2);
  • 4、Promisesobject

f1().then(f2);
function f1(){
    var dfd = $.Deferred();
    setTimeout(function () {
      //Task code of F1
      dfd.resolve();
    }, 500);
    return dfd.promise;
 }
f1();

The first four are more traditional, but also rely onjQueryThe expansibility and convenience are not strong when usingPlease check here for the specific codeThe following three methods are recommended.

  • 5、ES6 promise

  • 6、ES6 generator

  • 7、ES7 async and wait

4. Actual combat project

  • 1、Promise

Var promise = null; // define global variables
//New a promise object
promise = new Promise(function(resolve, reject) {
 Vue.http.jsonp('http://ipinfo.io/json').then(function(data)
      {
            if (data != null) {
                resolve(data);
            } else {
                reject("fail");
            }
        self.weatherData.city = data.data.city;
        self.weatherData.country = data.data.country;
        });
    })
//Chain transmission by promise
 promise.then(function(data) {
                        var city = data.data.city+data.data.country;
                        Vue.http.jsonp(api + city + units + appid).then(function(data) {
                            that.weatherShow(data);
                        });
                    })
summary
  • 1、promiseMainly solve the problem of callback

  • 2. Make the original multi-level nested code into a chain call

  • 3. Make the code clearer and reduce the number of nested

  • Disadvantages:PromiseThe biggest problem is code redundancy. The original task is packaged by promise. No matter what operation, it is a pile of then at a glance, and the original semantics becomes very unclear.
    demo

  • 2、generatorandyield

getLoc: function() {
                    var that = this;
                    Vue.http.jsonp('http://ipinfo.io/json').then(function(data) {
                        self.weatherData.city = data.data.city;
                        self.weatherData.country = data.data.country;
                        it.next(data.data);
                        //Focus 4
                    });
                },
                getCurrent: function(data) {
                    var that = this;
                    var api = "http://api.openweathermap.org/data/2.5/weather?q=";
                    var units = "&units=metric";
                    var appid = "&APPID=061f24cf3cde2f60644a8240302983f2"
                    var cb = "&callback=JSON_CALLBACK";
                    var city = data.city + ',' + data.country;
                    Vue.http.jsonp(api + city + units + appid).then(function(data) {
                        it.next(data);//Focus 4
                    });
//Focus 1
function* generator() {
                var data = yield object.getLoc();
                data = yield object.getCurrent(data);
                yield object.weatherShow(data);
            }
            Var it = generator(); // key 2
            it.next (); // key 3
summary
  • 1. Using the principle of iterator to solve the asynchronous problem

  • 2. Make the code clearer and reduce the number of nested.

  • Disadvantages: Although GeneratorFunction is very concise to express asynchronous operation, but process management is not convenient
    demo

  • 3、asyncandwait

getLoc: function() {
                    var that = this;
                    return new Promise(function(resolve, reject) {
                        Vue.http.jsonp('http://ipinfo.io/json').then(function(data) {
                            self.weatherData.city = data.data.city;
                            self.weatherData.country = data.data.country;
                            resolve(data.data);
                        });
                    })
                },
                getCurrent: function(data) {
                    var that = this;
                    var api = "http://api.openweathermap.org/data/2.5/weather?q=";
                    var units = "&units=metric";
                    var appid = "&APPID=061f24cf3cde2f60644a8240302983f2"
                    var cb = "&callback=JSON_CALLBACK";
                    var city = data.city + ',' + data.country;
                    return new Promise(function(resolve, reject) {
                        Vue.http.jsonp(api + city + units + appid).then(function(data) {
                            resolve(data);
                            // that.weatherShow(data);
                        });
                    });

                },
//Focus 1
 async function test() {
                const v1 = await object.getLoc();
                const v2 = await object.getCurrent(v1);
                const v3 = await object.weatherShow(v2);
            }
            test();
summary
  • 1. Solving asynchronous problems

  • 2、awaitInstead of following the thunk function, it must be followed by a promise object (therefore, promise is the ultimate solution and future of asynchrony). It is OK with other types of data, but it will be executed directly synchronously instead of asynchronously.

  • 3. Make the code clearer and reduce the number of nested.

  • 4. The readability of the code,async-awaitThe introduction is easier to read and more consistent with the semantics of the code. And there is no need to refer to the third-party library, and there is no need to learnGeneratorThe cost of using that pile of things is very low.
    demo

enclosedGitHub source codeIf you think it’s good, focus on it

Recommended Today

How does the new azure communication service (ACS) implement webrtc?

This article is from Gustavo Garcia, a software engineer of housepat. He has made a comprehensive evaluation of azure communication service (ACS), including browser compatibility, codec and bandwidth estimation algorithm. Compared with his main competitors, there is still a gap in maturity. By Gustavo Garcia Translated by Helen Lyu Original link/https://webrtchacks.com/how-d… We have a long […]