2014-05-23 3 views
12

배열을 사용하여 일부 작업을 수행하는 기능이 있습니다. 배열이 비어있을 때 거부하고 싶습니다. (가) 작업을 거부하는 예약속 거부 가능성이 처리되지 않음 오류 :

myArrayFunction(){ 
     return new Promise(function (resolve, reject) { 
      var a = new Array(); 
      //some operation with a 
      if(a.length > 0){ 
       resolve(a); 
      }else{ 
       reject('Not found'); 
      }   
     }; 
} 

으로

나는 다음과 같은 오류가 발생합니다. 아마도 처리되지 않은 오류 : 찾을 수 없음

그러나 myArrayFunction()에 대한 호출이 이루어지면 다음과 같은 오류가 발생합니다.

handlers.getArray = function (request, reply) { 
    myArrayFunction().then(
     function (a) { 
      reply(a); 
     }).catch(reply(hapi.error.notFound('No array'))); 
}; 

약속을 거부하고 거부하고 클라이언트에게 응답하는 올바른 방법은 무엇입니까?

감사합니다.

답변

18

는 매개 변수로 함수를 사용하지만 다른 것으로 전달합니다. 잡을 함수를 전달하지 않으면, 자동으로 아무것도하지 못합니다. 어리 석었지만 ES6이 약속 한 바입니다.

.catch은 아무 것도하지 않기 때문에 거절이 처리되지 않고보고됩니다.


수정은 .catch에 함수를 전달하는 것입니다 :

handlers.getArray = function (request, reply) { 
    myArrayFunction().then(function (a) { 
     reply(a); 
    }).catch(function(e) { 
     reply(hapi.error.notFound('No array'))); 
    }); 
}; 

모든 캐치를 사용하고 있기 때문에이 오류가 반드시 아니 배열 오류가 아닙니다.

추가로 단축 할 수
function myArrayFunction() { 
    // new Promise anti-pattern here but the answer is too long already... 
    return new Promise(function (resolve, reject) { 
      var a = new Array(); 
      //some operation with a 
      if (a.length > 0) { 
       resolve(a); 
      } else { 
       reject(hapi.error.notFound('No array')); 
      } 
     }; 
    } 
} 

function NotFoundError(e) { 
    return e.statusCode === 404; 
} 

handlers.getArray = function (request, reply) { 
    myArrayFunction().then(function (a) { 
     reply(a); 
    }).catch(NotFoundError, function(e) { 
     reply(e); 
    }); 
}; 

:

// Calls the method catch, with the function reply as an argument 
.catch(reply) 

그리고

// Calls the function reply, then passes the result of calling reply 
// to the method .catch, NOT what you wanted. 
.catch(reply(...)) 
:

handlers.getArray = function (request, reply) { 
    myArrayFunction().then(reply).catch(NotFoundError, reply); 
}; 

또한 사이의 차이를 유의 내가 대신 이렇게 제안

+0

픽스는 제안한대로 .catch 함수를 전달하는 것이 었습니다. 두 번째 옵션은 .catch (NotFoundError, reply)입니다. 나에게 다음과 같은 오류를 준다 "catch 필터는 에러 생성자 또는 필터 함수 여야한다." – juan

+0

@juan은 NotFoundError를 구현 했습니까? – Esailija

+0

예, 구현되었습니다. – juan

관련 문제