简体   繁体   中英

How to resolve promises and catch an error

I am trying to user webgazer.js where my code basically checks to see whether the webgazer is initialized and when it is initialized it resolves a promise which dispatches an action. This works however if for example there is no webcam I need to throw an error. The error in my code never gets called.

Here is my code

export function detectJsCamera() {
    return async(dispatch) => {
        dispatch({type: types.JS_DETECTING_CAMERA});
        try {
            await detectCamera();
            await dispatch({type: types.JS_CAMERA_DETECTED});
        } catch (error) {
            await dispatch({type: types.CAMERA_DETECTION_FAILED, error: error.message});
            throw error;
        // this.props.history.push('/setup/positioning')
    };
    }
}

const detectCamera = () => new Promise((resolve, reject) => {
    const checkIfReady = () => {
        if (webgazer.isReady()) {
        resolve('success');
        } else {
            console.log('called')
        setTimeout(checkIfReady, 100);
        }
    }
    setTimeout(checkIfReady,100);
});

You will need to reject in order to throw an exception like below

const detectCamera = () => new Promise((resolve, reject) => {
    const checkIfReady = () => {
        if (webgazer.isReady()) {
            resolve('success');
        } else {
            console.log('called');
            reject("some error");
        }
    }
    setTimeout(checkIfReady,100);
});

当未初始化Webgazer时,您需要在detectCamera方法中调用reject() ,否则它将在detectJsCamera方法的catch块中捕获。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM