简单粗暴的去重promise的回调

假设有这样一个场景,在用户快速点击刷新按钮后,短时间内会有多个网络请求发出,为了仅仅保留最新的一次请求,我们需要屏蔽之前发出请求的回调,不要因为异步回调顺序的不同导致页面刷新多次。

这里的做法是每次请求api的时候就保存当前的上下文环境(用唯一标识也是可以的),接到返回的时候判断这个返回是否是应该保留的,进而实现这个需求。

let context;

refresh() {
    context = {};

    new Promise((resolve, reject) => {
            let currentContext = context;

            post('xxx', {name: 'kale'})
                .then((json) => {
                    if (context === currentContext) {
                        resolve(json)
                    } else {
                        reject("CANCELED");
                    }
                })
                .catch((json) => {
                    if (context === currentContext) {
                        reject(json);
                    } else {
                        reject("CANCELED");
                    }
                })
        }
    ).then((json) => {
        // success
    }).catch((reason) => {
        if (reason !== "CANCELED") {
            // error
        }
    });
}
复制代码

猜你喜欢

转载自juejin.im/post/5b85f280f265da432008a2c6