그 전후에 어획물 배치
.catch
중첩 약속에 BEFORE와 AFTER를 넣는 것의 차이점을 이해하는 데 어려움이 있습니다.
대안 1 :
test1Async(10).then((res) => {
return test2Async(22)
.then((res) => {
return test3Async(100);
}).catch((err) => {
throw "ERROR AFTER THEN";
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
대안 2 :
test1Async(10).then((res) => {
return test2Async(22)
.catch((err) => {
throw "ERROR BEFORE THEN";
})
.then((res) => {
return test3Async(100);
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
각 함수의 동작은 다음과 같습니다. number가 <0
test2 이면 test1은 실패하고 number가 아니면 > 10
test3은 실패합니다 100
. 이 경우 test2는 실패 만합니다.
나는 실행하고 test2Async를 실패하게 만들려고했는데, BEFORE와 AFTER는 모두 같은 방식으로 작동하고 test3Async를 실행하지 않습니다. 누군가 다른 장소에 캐치를 배치하는 주요 차이점을 설명해 줄 수 있습니까?
각 기능 console.log('Running test X')
에서 실행 여부를 확인합니다.
이 질문은 내가 게시 한 이전 스레드 때문에 발생합니다 중첩 된 콜백을 약속으로 바꾸는 방법? . 나는 그것이 다른 문제이고 다른 주제를 게시 할 가치가 있다고 생각합니다.
따라서 기본적으로이 둘의 차이점이 무엇인지 묻습니다 ( p
이전 코드에서 생성 된 promise는 어디에 있습니까 ).
return p.then(...).catch(...);
과
return p.catch(...).then(...);
p가 해결하거나 거부 할 때 차이가 있지만 이러한 차이가 중요한지 여부는 .then()
또는 .catch()
핸들러 내부의 코드가 수행하는 작업에 따라 다릅니다 .
p
해결 되면 어떻게 되나요?
첫 번째 체계에서 p
해결되면 .then()
처리기가 호출됩니다. 해당 .then()
핸들러가 값이나 결국 해결되는 다른 promise를 반환하면 .catch()
핸들러를 건너 뜁니다. 그러나 .then()
핸들러가 결국 거부하는 promise를 던지거나 반환하는 경우 .catch()
핸들러는 원래 promise의 거부와 핸들러 p
에서 발생하는 오류 모두에 대해 실행됩니다 .then()
.
두 번째 체계에서는 p
해결 될 때 .then()
처리기가 호출됩니다. 해당 .then()
핸들러가 결국 거부하는 프라 미스를 던지거나 리턴하면 .catch()
핸들러가 체인에서 앞에 있기 때문에이를 포착 할 수 없습니다.
그래서 이것이 차이점 # 1입니다. 는 IF .catch()
처리기 이후, 그것은 또한 내부 오류를 잡을 수 .then()
처리기를.
p
거부 하면 어떻게 되나요?
이제 첫 번째 체계에서 promise가 p
거부되면 .then()
핸들러를 건너 뛰고 .catch()
예상대로 핸들러가 호출됩니다. .catch()
처리기 에서 수행하는 작업에 따라 최종 결과로 반환되는 내용이 결정됩니다. .catch()
핸들러 에서 값을 반환하거나 결국 해결되는 promise를 반환하면 오류를 "처리"하고 정상적으로 반환했기 때문에 promise 체인이 해결 된 상태로 전환됩니다. .catch()
핸들러 에서 거부 된 promise를 던지거나 반환 하면 반환 된 promise는 거부 된 상태로 유지됩니다.
두 번째 체계에서 promise가 p
거부되면 .catch()
핸들러가 호출됩니다. 정상 값이나 결국 .catch()
처리기 에서 해결되는 약속을 반환하면 (따라서 오류를 "처리") promise 체인이 해결 된 상태로 전환되고 .then()
이후 처리기 .catch()
가 호출됩니다.
이것이 차이점 # 2입니다. 는 IF .catch()
핸들러가 전입니다, 그것은 오류를 처리하고 허용 할 수 .then()
처리기가 여전히 전화를받을 수 있습니다.
사용시기 :
.catch()
원래 프라 미스 p
또는 .then()
핸들러 에서 오류를 포착 할 수있는 핸들러 하나만 원하는 경우 첫 번째 스킴을 사용하고 거부에서 핸들러를 p
건너 뛰어야 .then()
합니다.
Use the second scheme if you want to be able to catch errors in the original promise p
and maybe (depending upon conditions), allow the promise chain to continue as resolved, thus executing the .then()
handler.
The other option
There's one other option to use both callbacks that you can pass to .then()
as in:
p.then(fn1, fn2)
This guarantees that only one of fn1
or fn2
will ever be called. If p
resolves, then fn1
will be called. If p
rejects, then fn2
will be called. No change of outcome in fn1
can ever make fn2
get called or vice versa. So, if you want to make absolutely sure that only one of your two handlers is called regardless of what happens in the handlers themselves then you can use p.then(fn1, fn2)
.
jfriend00's answer is excellent, but I thought it would be a good idea to add the analogous synchronous code.
return p.then(...).catch(...);
is similar to the synchronous:
try {
iMightThrow() // like `p`
then()
} catch (err) {
handleCatch()
}
If iMightThrow()
doesn't throw, then()
will be called. If it does throw (or if then()
itself throws), then handleCatch()
will be called. Notice how the catch
block has no control over whether or not then
is called.
On the other hand,
return p.catch(...).then(...);
is similar to the synchronous:
try {
iMightThrow()
} catch (err) {
handleCatch()
}
then()
In this case, if iMightThrow()
doesn't throw, then then()
will execute. If it does throw, then it would be up to handleCatch()
to decide if then()
is called, because if handleCatch()
rethrows, then then()
will not be called, since the exception will be thrown to the caller immediately. If handleCatch()
can gracefully handle the issue, then then()
will be called.
참고URL : https://stackoverflow.com/questions/42013104/placement-of-catch-before-and-after-then
'your programing' 카테고리의 다른 글
둘 다에 대해 0-255 범위에서 RGB를 HSV로, HSV를 RGB로 변환하는 알고리즘 (0) | 2020.10.11 |
---|---|
phpMyAdmin에서 데이터베이스 삭제 (0) | 2020.10.11 |
Python의 중첩 함수 (0) | 2020.10.11 |
중복 키를 허용하는 C # 정렬 가능한 컬렉션 (0) | 2020.10.10 |
절대 위치 + 스크롤링 (0) | 2020.10.10 |