Last active
December 27, 2018 11:18
-
-
Save jruif/3d2ec9f61441f1d0b06876ebc78fb89c to your computer and use it in GitHub Desktop.
模拟takeLatest,处理竞态问题
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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