How uni-app calls an asynchronous request to resolve the problem get out of sequence data for the cycle in?

Summary / Zhuji Qian

Once done a previous uni-app js when the docking interface, such a situation encountered in the for loop, an asynchronous invocation request, the return value is arbitrary order, and therefore, in the following code, to Push array of values, each order may have been different, cause such a reason, is the for loop is single-threaded, asynchronous request is multithreaded, f often at the end of the for loop, asynchronous requests is not over yet.

 

that.list = res.datas.class_list;
                            
for(var i=0;i<that.list.length;i++){
   that.list[i].tlist = []
var url = "w=goods_class&gc_id=" + that.list[i].gc_id.substring(2);
    that.thtxb_ajax_request(url, {}).then((res) => {
        that.tlist.push(res.datas.class_list)
        })
    }

In uni-app framework, similar encountered such codes, recursive algorithm can be used to avoid the end of the for loop, the problem of the asynchronous request is not over, the above code changes into a recursive form, the following:

that.list = res.datas.class_list;
                            
    var i = 0;

    getImg();
    function getImg() {
        if (i >= that.list.length) {
        return;
    }
    that.list[i].tlist = []
    var url = "w=goods_class&gc_id=" + that.list[i].gc_id.substring(2);
    that.thtxb_ajax_request(url, {}).then((res) => {
        that.tlist.push(res.datas.class_list)
        i++
        getImg();
        })
    }

According to this modification, calls can be avoided for the cycle in the asynchronous request problems.

 

Other js can also follow this line of thought, the idea of ​​using a recursive algorithm.

Guess you like

Origin www.cnblogs.com/zhujiqian/p/11532935.html