Skip to content

Instantly share code, notes, and snippets.

@xigh
Last active May 29, 2020 12:07
Show Gist options
  • Save xigh/dd9645336ed3d172fd5f647447e6f8b4 to your computer and use it in GitHub Desktop.
Save xigh/dd9645336ed3d172fd5f647447e6f8b4 to your computer and use it in GitHub Desktop.
Promise based Asynchronous Queue
export class PromiseQ {
constructor() {
this._queue = [];
}
async append(callback, param) {
const self = this;
const process = () => {
if (self._queue.length == 0) {
return;
}
const next = () => {
self._queue.shift();
process();
}
const x = self._queue[0];
const resolve = (data) => {
x.resolve(data);
next();
}
const reject = (data) => {
x.reject(data);
next();
}
x.callback(resolve, reject, x.data);
}
return new Promise((resolve, reject) => {
const n = this._queue.push({
resolve: resolve,
reject: reject,
callback: callback,
data: param,
});
if (n == 1) {
process();
}
})
}
}
import { ajax } from "./xhrpq.js";
window.addEventListener('load', () => {
for (let i = 0; i < 10; i++) {
ajax('GET', `./img/${i}.png`, 'arraybuffer')
.then((xhr) => {
console.log(`received ${xhr.response.byteLength} bytes`);
})
.catch((xhr) => {
console.log(`failed with ${xhr.status}`);
})
;
}
});
import { PromiseQ } from "./pq.js";
const pq = new PromiseQ();
function process(resolve, reject, param) {
const xhr = new XMLHttpRequest();
xhr.open(param.method, param.url);
if (param.type) {
xhr.responseType = param.type;
}
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr);
} else {
reject(xhr);
}
}
}
xhr.send(param.data);
}
/**
*
* @param {string} method
* @param {string} url
*/
export async function ajax(method, url, type, data) {
return pq.append(process, {
method: method,
url: url,
type: type,
data: data,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment