-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Promise.all 调用接口并发请求控制 #15
Labels
coding
test or practice
Comments
解决方法 1 let count = 0;
const memo = {};
/**
* @param uid uid
* @param max 最多并发请求数量
*/
const requestUserProfile = async (uid = '1', max = 2) => {
// 这里调用requestProfile 进行优化
let timer;
const loopRequestProfile = (resolve: any) => {
timer && cancelAnimationFrame(timer);
if (memo[uid]) {
return resolve(memo[uid])
}
if (max > count) {
count += 1;
requestProfile(uid).then((data) => {
count -= 1;
memo[uid] = data;
resolve(data);
});
} else {
// 循坏调用 loopRequestProfile 直到 count < max
timer = requestAnimationFrame(() => {
loopRequestProfile(resolve);
});
}
};
return new Promise(loopRequestProfile);
} |
✅ 解决方法2 (终于解出来了) let count = 0;
const taskQueue = [];
/**
* @param uid uid
* @param max 最多并发请求数量
*/
const requestUserProfile = (uid = '1', max = 2) => {
const pullTask = () => {
if (taskQueue.length === 0) {
return;
}
if (count === max) {
return;
}
count++;
const { resolve, uid } = taskQueue.shift();
resolve(runTask(uid));
};
const runTask = (id) => {
const promise = requestProfile(id);
promise.then(() => {
count--;
pullTask();
});
return promise;
};
return new Promise((resolve) => {
taskQueue.push({ resolve, uid });
if (count < max) {
count++;
const { resolve, uid } = taskQueue.shift();
resolve(runTask(uid));
}
});
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
目标
优化
requestUserProfile
并发请求要求
requestUserProfile
是个通用用户信息接口,通过传入uid,拿用户昵称The text was updated successfully, but these errors were encountered: