이 코드가 있다고 가정 해 봅시다.
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
return;//This only exists the this arrow funtion
});
console.log('Should not get to here if foo rejects');
}
경우 foo
반환 거부 약속, 그때 종료하고 싶습니다 doSomething()
,하지만 위의 코드는이 작업을 수행하지 않습니다. 대신가 error
포착되었으므로 코드가 계속됩니다.
catch
거부 된 약속을 수행하지 않으면 오류가 발생합니다. UnhandledPromiseRejectionWarning
:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
console.log('Should not get to here if foo rejects');
}
나는 이것을 할 수 있다는 것을 알고 있지만 이것은 단지 지저분하다.
function doSomething() {
let exitFunction = false;
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
exitFunction = true;
});
if (exitFunction) {
return;
}
console.log('Should not get to here if foo rejects');
}
그렇다면 이와 같은 것을 처리하는 가장 좋은 방법은 무엇입니까? 이렇게 할 수 있으면 좋을 것입니다.
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
if (foo.rejected) {
return;
}
console.log('Should not get to here if foo rejects');
}
또는 이것도 :
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
return function2;//Sort of like JS's `break loop2;`
});
console.log('Should not get to here if foo rejects');
}
다른 사람이 내 고통을 느끼는가? 그렇다면 이것을 처리하는 가장 좋은 (가장 깨끗한) 방법은 무엇입니까?
try/catch
약속을 처리 하는 경우 사용 하는 것이 좋습니다 .async function
function promiseFunc() {
return new Promise((resolve, reject) => {
//...
reject("error!");
});
}
async function doSomething() {
try {
const foo = await promiseFunc();
} catch (err) {
console.log(err);
return;
}
console.log("Should not get to here if foo rejects");
}
doSomething();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다