模拟ajax的同异步

今天突然想到那只在app中,如果请求数据时用的是app提供的接口,如果该接口没有同异步的话,怎么办。

所以就捣腾了下。 模拟ajax同异步。

 1 var VshopDataApi = {
 2     queryArr : [], // { code : [{code, data, callback, is_sync}]}//系统队列
 3     is_sync  : false, //是否同步 默认false 不同步 系统变量
 4     ajax     : function(item, callback){ //自定义
 5         // var time = parseInt(Math.random() * 100);
 6         // console.log('+++++发送成功+'+item.code+'+++++');
 7         // setTimeout(function (){
 8         //     //模拟 不定时回调
 9         //     callback( '顺序:'+item.code+' '+(item.is_sync ? '同步' : '异步'));
10         // }, time * 100);
11     }
12 }
13 
14 
15 /**
16  * 进队列
17  * @param  {object} item 必须包含 字段 callback:回调函数, is_sync:是否同步
18  */
19 VshopDataApi.push = function(item){
20     item.is_sync = item.is_sync || false;
21 
22     if (this.is_sync) {
23         this.queryArr.push(item);
24         return;
25     }
26 
27     if (item.is_sync) {
28         this.is_sync = item.is_sync;
29     }
30 
31     //发送
32     VshopDataApi._ajax(item);
33     
34 };
35 
36 //出队列
37 VshopDataApi.shift = function(){
38     if (this.queryArr.length <= 0) {return;}
39     var item = {};
40     item = this.queryArr.shift();
41     this.is_sync = item.is_sync;
42     this._ajax(item);
43     if (!this.is_sync) {
44         this.shift();
45     }
46 
47 };
48 
49 //系统执行
50 VshopDataApi._ajax = function(item){
51     var _this = this;
52     (function(item){
53 
54         _this.ajax(item,function(result){
55             item.callback(result);
56 
57             if (item.is_sync) {
58                 _this.shift();
59             }item = null;
60         });
61     })(item);
62 };
63 
64 //回调函数
65 function callback(result){
66     console.log('---------callback begin----------');
67     console.log(result);
68     console.log('--------callback end---------');
69 };
70 
71 //重写
72 VshopDataApi.ajax  = function(item, callback){ //自定义
73         var time = parseInt(Math.random() * 100);
74         console.log('+++++发送成功+'+item.code+'+++++');
75         setTimeout(function (){
76             //模拟 不定时回调
77             callback( '顺序:'+item.code+' '+(item.is_sync ? '同步' : '异步'));
78         }, time * 100);
79     }
80 
81 //进队列
82 VshopDataApi.push({code : '1', data: {}, callback : callback, is_sync : false });
83 VshopDataApi.push({code : '2', data: {}, callback : callback, is_sync : true });//同步
84 VshopDataApi.push({code : '3', data: {}, callback : callback, is_sync : false });
85 VshopDataApi.push({code : '4', data: {}, callback : callback, is_sync : false });
86 VshopDataApi.push({code : '5', data: {}, callback : callback, is_sync : true });//同步
87 VshopDataApi.push({code : '6', data: {}, callback : callback, is_sync : false });
88 VshopDataApi.push({code : '7', data: {}, callback : callback, is_sync : true });//同步
89 VshopDataApi.push({code : '8', data: {}, callback : callback, is_sync : false });

回调时特地写个随机时间。 看看如果同步的先执行成功,会不会继续执行。

结果:

原文地址:https://www.cnblogs.com/songbyjson/p/4802104.html