Promise与setTimeout的错误示范

错误写法

export const checkSDK = () => {
    var timer = null;
    const start = Date.now();

    return new Promise((resolve, reject) => {
        if (typeof window.TigerBridge === 'object') {
            resolve();
            return;
        }
        if (Date.now() - start <= 5 * 1000) {
            clearTimeout(timer);
            timer = setTimeout(checkSDK, 100);
            return;
        }

        reject();
    })
}

正确写法

export const checkBridge = () => {
    var timer = null;
    const start = Date.now();

    function check(resolve, reject) {
        if (typeof window.TigerBridge === 'object') {
            resolve();
            return true;
        } 
        if (Date.now() - start <= 5 * 1000) {
            clearTimeout(timer);
            timer = setTimeout(check.bind(null, resolve, reject), 100);
            return;
        }
        reject();
        return false;
    }

    return new Promise((resolve, reject) => check(resolve, reject))
}

模仿SDK注入过程,

if (process.env.NODE_ENV != 'production') {
    setTimeout(() => {
        window.TigerBridge = {
            getAccessToken: () => {
                return pkg.token;
            },
            isAccountPermissionLimited: () => false
        };
    }, 1600);
}

相关推荐