Skip to content

Instantly share code, notes, and snippets.

@jruif
Last active December 27, 2018 11:18
Show Gist options
  • Select an option

  • Save jruif/3d2ec9f61441f1d0b06876ebc78fb89c to your computer and use it in GitHub Desktop.

Select an option

Save jruif/3d2ec9f61441f1d0b06876ebc78fb89c to your computer and use it in GitHub Desktop.

Revisions

  1. jruif revised this gist Dec 27, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion takeLatest.js
    Original file line number Diff line number Diff line change
    @@ -32,4 +32,4 @@ for (let index = 0; index < 4; index++) {
    // todo: 处理结果
    console.log(n);
    });
    }
    }
  2. jruif created this gist Dec 27, 2018.
    35 changes: 35 additions & 0 deletions takeLatest.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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);
    });
    }