Skip to content

Instantly share code, notes, and snippets.

@jruif
Last active December 27, 2018 11:18
Show Gist options
  • Save jruif/3d2ec9f61441f1d0b06876ebc78fb89c to your computer and use it in GitHub Desktop.
Save jruif/3d2ec9f61441f1d0b06876ebc78fb89c to your computer and use it in GitHub Desktop.
模拟takeLatest,处理竞态问题
function takeLatest(asyncFunc) {
let index = 0;
return (...argv) => {
function execNext(func, reqIndex) {
return (...argv2) => {
if (reqIndex === index) {
func.call(this, ...argv2);
}
};
}
return new Promise((resolve, reject) => {
index++;
asyncFunc.call(this, ...argv).then(execNext(resolve, index), execNext(reject, index));
});
};
}
// 异步函数
const timeout = name =>
new Promise(resolve => {
setTimeout(() => {
resolve(name);
}, 500);
});
const a = takeLatest(timeout);
// 模拟频繁触发
for (let index = 0; index < 4; index++) {
a(index).then(n => {
// todo: 处理结果
console.log(n);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment