2014-10-17 5 views
0

요즘 많이 사용하고 있습니다. ES6 Promises입니다.console.error가 함수가 아닌 메서드 인 이유는 무엇입니까?

new Promise(function(resolve, reject) { 
    resolve(doCrazyThingThatMightThrowAnException()); 
}).then(function(result) { 
    return performDangerousTranformation(result); 
}); 

내가 할 catch()를 사용하여 몇 바이트를 추가 할 수 있다면 정말 좋을 것 확인 예외를 만드는 : 따라서, 당신이 onRejected 기능을 지정하지 않을 경우 예외 추적을 잃고 쉽게 콘솔에 : console.error이 방법보다는 기능 때문에

new Promise(function(resolve, reject) { 
    resolve(doCrazyThingThatMightThrowAnException()); 
}).then(function(result) { 
    return performDangerousTranformation(result); 
}).catch(console.error); 

불행히도,이 작동하지 않습니다. 즉, console.error()을 호출 할 때 수신자 console을 지정해야합니다.

> console.error('err'); 
prints err 
> var f = console.error; 
> f('err'); 
throws Illegal invocation exception 

이 내 catch() 핸들러를 추가하는 것은 좀 더 자세한 것을 의미한다 : 틀림

new Promise(function(resolve, reject) { 
    resolve(doCrazyThingThatMightThrowAnException()); 
}).then(function(result) { 
    return performDangerousTranformation(result); 
}).catch(function(error) { console.error(error); }); 

, 그것은 조금 더 나은 ES6에서이다 : 당신은 자신을 브라우저 콘솔에서 매우 쉽게이를 확인할 수 있습니다

new Promise(function(resolve, reject) { 
    resolve(doCrazyThingThatMightThrowAnException()); 
}).then(function(result) { 
    return performDangerousTranformation(result); 
}).catch((error) => console.error(error)); 

하지만 추가 타이핑을 피하는 것이 좋습니다. 더 나쁜 것은 오늘 catch(console.error)을 사용하면 예외가 자동으로 무시된다는 것입니다. 이는 정확히 해결하려는 문제입니다! 방법이 될 필요가있는 방법이 무엇입니까 console.error() 근본적인 것이 있습니까? 종교 허용하는 경우

+2

'console.error.bind (console)' –

+0

이것은 구현에 달렸으며, "함수로"작동하는 구현을 발견 할 수도 있습니다. – Volune

+0

왜 오류에 대한 함수를 작성하지 않습니까? 'var err = function() {console.error.apply (console, arguments);}'내가 뭔가를 놓쳤습니까? – GramThanos

답변

0

당신은 약속 개체를 확장 할 수 있습니다 : 다음

Promise.prototype.catchLog = function() { 
    return this.catch(
     function(val) { 
      console.log("Promise has rejected with reason", val); 
      throw val;   // continue with rejected path 
     } 
    ); 
}; 

function crazy() { throw 99; } 

Promise.resolve() 
    .then(crazy) 
    .catchLog(); 

>>> Promise has rejected with reason 99 

당신은 "몇 바이트"와 거부에 대한 로깅을 추가 할 수있는 요청; 이 부분은 catch의 끝에 3 개 (L-o-g)입니다.

관련 문제