[英]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. 我正在尝试使用
webgazer.js
,在这里我的代码基本上检查以查看webgazer
是否已初始化,并且在初始化时它解析了调度动作的promise。 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块中捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.