Skip to content

Instantly share code, notes, and snippets.

@alsotang
Created August 6, 2020 15:57
Show Gist options
  • Save alsotang/31108dee4bca564e4c65462599eb182b to your computer and use it in GitHub Desktop.
Save alsotang/31108dee4bca564e4c65462599eb182b to your computer and use it in GitHub Desktop.
重复调用异步函数时,批量返回首次调用的结果
async function _getCgiData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('cgi data')
}, 5000);
})
}
let isGetting = false;
let getCgiQueue = []
async function getCgiData() {
if (isGetting) {
return new Promise(resolve => {
getCgiQueue.push(resolve);
})
}
isGetting = true;
const res = await _getCgiData();
getCgiQueue.forEach(resolve => {
resolve(res);
})
getCgiQueue = [];
isGetting = false;
return res
}
async function main() {
setTimeout(async () => {
const res = await getCgiData();
console.log(`res1`, res, new Date())
}, 0);
setTimeout(async () => {
const res = await getCgiData();
console.log(`res2`, res, new Date())
}, 1000);
setTimeout(async () => {
const res = await getCgiData();
console.log(`res3`, res, new Date())
}, 2000);
setTimeout(async () => {
const res = await getCgiData();
console.log(`res4`, res, new Date())
}, 3000);
setTimeout(async () => {
const res = await getCgiData();
console.log(`res5`, res, new Date())
}, 6000);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment