Skip to content

Instantly share code, notes, and snippets.

@ztrehagem
Created May 18, 2019 03:46
Show Gist options
  • Save ztrehagem/0c47f842893b01b28e5021082f81edd8 to your computer and use it in GitHub Desktop.
Save ztrehagem/0c47f842893b01b28e5021082f81edd8 to your computer and use it in GitHub Desktop.
const axios = {
get: (...args) => new Promise((resolve, reject) => {
console.log('called', args.join(', '));
setTimeout(() => resolve(args.join(', ')), 1500);
}),
};
const api = {
get: (...args) => new Promise((resolve, reject) => {
queue.push(async () => {
try {
resolve(await axios.get(...args)); // 本物
} catch (e) {
reject(e);
}
});
console.log('queued', args.join(', '));
checkQueue();
}),
};
const queue = [];
let current = null; // 実行中の関数を入れとく
async function checkQueue() { // キューを頭から消化していく
console.log('checkQueue');
if (current || !queue.length) return;
current = queue.shift();
await current();
current = null;
checkQueue();
}
async function main() {
const p1 = api.get('/hoge', 1);
const p2 = api.get('/fuga', 2);
p1.then(r1 => console.log('got', r1));
p2.then(r2 => console.log('got', r2));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment