how to temporarily encapsulate events in promise then mode into a queue, and then traverse the queue to execute the corresponding events!
actual scene:
Requests in theajax layer rely on some shared data, but do not want to control the logic of this dependency at the business layer. Want to centralize processing in the event queue of the ajax wrapper layer! The business layer only needs to provide fields that depend on parameters!
< H2 > remarks < / H2 >traditional callback mode queue implementation
"use strict";
window.personal = window.personal || {};
personal.ajax = personal.ajax || {};
let ajaxQueue = [];
let promiseQueue = [];
let flag = false;
(function () {
let _this = this;
// callback
this._ajax = function (params) {
if (!flag) {
ajaxQueue.push(params);
return;
}
$.ajax({
type: params.type || "get",
url: params.url,
data: params.data || {},
success: function (data, status, xhr) {
params.callback(data, status, xhr);
},
error: function (xhr, errorType, error) {
params.callback(xhr, errorType, error);
}
})
}
this.axiosCallback = function (params) {
if (!flag) {
promiseQueue.push(params);
} else {
return axiosAjax(params, false)
}
}
}).call(personal.ajax);
function axiosAjax(params, isPromise = true) {
params.type = params.type || "get";
// get/post
const _data = params.type === "get" ? {
params: params.data
} : {
data: params.data
};
const _config = Object.assign({
method: params.type,
url: params.url
}, _data);
return axios(_config).then((res = {}) => {
return isPromise ? res.data : void params.callback(res.data, 100, "ok");
}).catch((err = {}) => {
return isPromise ? err : void params.callback(err, 0, "err");
})
}
_timer(function () {
if (ajaxQueue.length) {
console.log("flag=>" + flag)
personal.ajax._ajax(ajaxQueue.shift());
personal.ajax.axiosCallback(promiseQueue.shift());
}
}, 100);
setTimeout(function () {
flag = true;
console.log("------flag-----")
}, 1500);
/**
*
* @param callback
* @param timeout
*/
function _timer(callback, timeout = 1000) {
let _flag = true;
(function _inner() {
//
// callback();
let _timer = _flag && setInterval(() => {
_timer && clearInterval(_timer);
//or
callback();
_inner(callback, timeout);
}, timeout);
})();
return function close() {
_flag = false;
}
}