처리되지 않은 약속 거부 란 무엇입니까?
Angular 2를 배우기 위해 튜토리얼을 시도하고 있습니다.
다음과 같은 오류가 발생합니다.
(node:4796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r ejection id: 1): Error: spawn cmd ENOENT
[1] (node:4796) DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.
js process with a non-zero exit code.
나는 SO에서 다른 질문과 답변을 겪었지만 "처리되지 않은 약속 거부"가 무엇인지 알 수 없었습니다.
누구나 그것이 무엇 Error: spawn cmd ENOENT
이고 무엇 이고 언제 발생하는지, 그리고이 경고를 제거하기 위해 확인해야 할 것을 설명 할 수 있습니까?
이 오류의 근원은 각각의 모든 약속이 약속 거부를 처리해야한다는 것, 즉 .catch (...)를 가지고 있다는 사실에 있습니다 . 아래 주어진 코드의 약속에 .catch (...) 를 추가하여 동일한 것을 피할 수 있습니다.
예를 들어, 함수 PTest ()는 전역 변수 somevar 의 값을 기반으로 약속을 해결하거나 거부합니다 .
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
}).catch(function () {
console.log("Promise Rejected");
});
경우에 따라 약속되지 않은 .catch (..)가 있어도 "처리되지 않은 약속 거부" 메시지가 나타납니다. 코드 작성 방법에 관한 모든 것입니다. 다음 코드는 처리 하고 있지만 "처리되지 않은 약속 거부"를 생성 catch
합니다.
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
console.log("Promise Rejected");
});
차이점은 .catch(...)
체인으로 취급하지 않고 별개로 처리한다는 것 입니다. 어떤 이유로 JavaScript 엔진은 처리되지 않은 약속 거부없이 약속으로 취급합니다.
이것은 a Promise
로 완료 .reject()
되거나 async
실행 코드 에서 예외가 발생 .catch()
하고 거부를 처리 하지 않은 경우입니다.
거부 된 약속은 응용 프로그램 진입 점을 향해 거품이 발생하여 근본 오류 처리기가 해당 출력을 생성하는 예외와 같습니다.
또한보십시오
- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Promises can be "handled" after they are rejected. That is, one can call a promise's reject callback before providing a catch handler. This behavior is a little bothersome to me because one can write...
var promise = new Promise(function(resolve) {
kjjdjf(); // this function does not exist });
... and in this case, the Promise is rejected silently. If one forgets to add a catch handler, code will continue to silently run without errors. This could lead to lingering and hard-to-find bugs.
In the case of Node.js, there is talk of handling these unhandled Promise rejections and reporting the problems. This brings me to ES7 async/await. Consider this example:
async function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
let temp = await tempPromise;
// Assume `changeClothes` also returns a Promise
if(temp > 20) {
await changeClothes("warm");
} else {
await changeClothes("cold");
}
await teethPromise;
}
In the example above, suppose teethPromise was rejected (Error: out of toothpaste!) before getRoomTemperature was fulfilled. In this case, there would be an unhandled Promise rejection until await teethPromise.
My point is this... if we consider unhandled Promise rejections to be a problem, Promises that are later handled by an await might get inadvertently reported as bugs. Then again, if we consider unhandled Promise rejections to not be problematic, legitimate bugs might not get reported.
Thoughts on this?
This is related to the discussion found in the Node.js project here:
Default Unhandled Rejection Detection Behavior
if you write the code this way:
function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
return Promise.resolve(tempPromise)
.then(temp => {
// Assume `changeClothes` also returns a Promise
if (temp > 20) {
return Promise.resolve(changeClothes("warm"));
} else {
return Promise.resolve(changeClothes("cold"));
}
})
.then(teethPromise)
.then(Promise.resolve()); // since the async function returns nothing, ensure it's a resolved promise for `undefined`, unless it's previously rejected
}
When getReadyForBed is invoked, it will synchronously create the final (not returned) promise - which will have the same "unhandled rejection" error as any other promise (could be nothing, of course, depending on the engine). (I find it very odd your function doesn't return anything, which means your async function produces a promise for undefined.
If I make a Promise right now without a catch, and add one later, most "unhandled rejection error" implementations will actually retract the warning when i do later handle it. In other words, async/await doesn't alter the "unhandled rejection" discussion in any way that I can see.
to avoid this pitfall please write the code this way:
async function getReadyForBed() {
let teethPromise = brushTeeth();
let tempPromise = getRoomTemperature();
// Change clothes based on room temperature
var clothesPromise = tempPromise.then(function(temp) {
// Assume `changeClothes` also returns a Promise
if(temp > 20) {
return changeClothes("warm");
} else {
return changeClothes("cold");
}
});
/* Note that clothesPromise resolves to the result of `changeClothes`
due to Promise "chaining" magic. */
// Combine promises and await them both
await Promise.all(teethPromise, clothesPromise);
}
Note that this should prevent any unhandled promise rejection.
"DeprecationWarning: Unhandled promise rejections are deprecated"
TLDR: A promise has resolve
and reject
, doing a reject
without a catch to handle it is deprecated, so you will have to at least have a catch
at top level.
When I instantiate a promise, I'm going to generate an asynchronous function. If the function goes well then I call the RESOLVE then the flow continues in the RESOLVE handler, in the THEN. If the function fails, then terminate the function by calling REJECT then the flow continues in the CATCH.
In NodeJs are deprecated the rejection handler. Your error is just a warning and I read it inside node.js github. I found this.
DEP0018: Unhandled promise rejections
Type: Runtime
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.
참고URL : https://stackoverflow.com/questions/40500490/what-is-an-unhandled-promise-rejection
'Programing' 카테고리의 다른 글
display : flex를 사용하여 CSS로 남은 수직 공간 채우기 (0) | 2020.06.08 |
---|---|
스프링 부트 REST 서비스 예외 처리 (0) | 2020.06.08 |
자바에서 XML 파싱을위한 최고의 라이브러리는 무엇입니까? (0) | 2020.06.08 |
iPhone 웹 응용 프로그램에서 방향을 세로 모드로 잠 그려면 어떻게합니까? (0) | 2020.06.08 |
SignalR은 어떻게 내부적으로 작동합니까? (0) | 2020.06.08 |