【问题标题】:Run callback in the function only if there is no new calls of the function只有在没有新的函数调用时才在函数中运行回调
【发布时间】:2020-04-07 14:46:42
【问题描述】:

我在项目中有一个组件,它接受一个带有回调参数的函数。在更改此组件时,此函数在内部调用。但这里有一个问题,我们在每次更改时使用async await 函数异步获取一些数据,在我们获取一些数据后我们会进行回调。因此,在第二次更改时,我可以看到带有旧数据的回调调用。由于async,标准去抖动在这里不起作用。

这是我的快速关闭解决方案:

function doOnlyLastFunction(fnc) {
    let id = 0;
    const isLast = (currentId) => () => currentId === id;
    return (...args) => {
        id++;
        fnc.call(this, ...args, isLast);
    };
}

很快在运行时:

let closure = null;
function handler(data, cb) {
    if (!closure) {
        closure = doOnlyLastFunction(async (data, cb, isLast) => {
            //await some promises
            if (isLast()) {
                cb(result); //cb with data
            }         
        });
    }
    closure(data, cb);
}

我这是一个糟糕的解决方案,我无法在顶层更改逻辑。有没有办法优化这个逻辑?

【问题讨论】:

  • 我无法在顶层更改逻辑。”是什么意思?
  • @Bergi 我无法重写组件逻辑和承诺的逻辑

标签: javascript asynchronous closures


【解决方案1】:

我建议将 isLast() 检查移动到您的 fnc 正在调用的回调内部:

function doOnlyLastFunction(fn) {
    let id = 0;
    return function(...args) {
        const currentId = ++id;
        const cb = args.pop();
        fn.call(this, ...args, function(...results) {
            if (currentId === id)
                cb(...results);
        });
    };
}

您也不需要从handler 内部懒惰地初始化您的closure 变量。去吧

const handler = doOnlyLastFunction(async (data, cb) => {
    //await some promises
    cb(result); //cb with data
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多