2017-09-28 1 views
0

나는 내 약속 체인의 성공/오류를 출력하려고 애 쓰고 있습니다. 나는이AWS 람다 핸들러 내에서 콜백 사용

exports.handler = function(event, context, callback) { 
    Q.allSettled(init()).then(function (result) { 

    requestValid(event.queryStringParameters) 
     .then(isDuplicate) 
     .then(process) 
     .then(insertData) 
     .then(displayResponse) 
     .catch(function (error) { 
      // Handle any error from all above steps 
      console.error(
       'Error: ' + error 
      ); 
      callback({ 
       statusCode: 500, 
       body: JSON.stringify({ 
        message: error 
       }, null) 
      }); 
     }) 
     .done(function() { 
      console.log(
       'Script Finished' 
      ); 
      callback(null, { 
       statusCode: 200, 
       body: JSON.stringify({ 
        message: 'Done' 
       }) 
      }); 
     }); 
    }); 
}; 

처럼 함께 약속을 체인하고

나는 약속의 내부 성공 실패에 Q.defer.reject(error_message);Q.defer.resolve(success_message)를 호출하고 있습니다. 이러한 약속 중 하나라도 실패하면 .catch(function (error) {에 오류가 있습니다.

모두 괜찮지 만이 데이터를 처리기의 콜백에 반환하는 방법은 무엇입니까?

exports.handler = function (event, context, callback) { 
    let response = { 
     statusCode: 200, 
     body: JSON.stringify('some success or error') 
    }; 

// Return all of this back to the caller (aws lambda) 
    callback(null, response); 
}; 

내가하고 싶은,하지만 어디 때문에 약속의 넣어하지 않는 방법 /하는 일의 예 ... .. 사전에

+1

AWS API 게이트웨이로 comminucating하는 것 같습니다. 어쨌든 모든 기능을 화살표 기능으로 바꾸고 작동하는지 알려주세요! –

+2

질문을 정리해 주시겠습니까? 먼저 오류가 발생해도 'null'값으로 콜백을 호출하는 이유는 무엇입니까? 실제로 함수의 현재 동작은 무엇입니까? 타임 아웃이나 무엇을 통해서만 완료됩니까? –

+0

@ArtemArkhipov 약속을 사용할 때 콜백 함수를 올바르게 사용하고 싶습니다. 나는 이것을 업데이트했다. 나는이 콜백을 람다에게만 돌려주기를 원했기 때문에 어떤 매개 변수가 사용되었는지는 중요하지 않다는 인상을 받았다. 나는 그들이 오류에 대한 것이고 다른 하나는 성공에도 불구하고 그들이 다르게 행동했다는 것을 알지 못했습니다. –

답변

0

Chain your promises all the way you usually do it을 주셔서 감사합니다. 체인의 마지막 단계에서 결과를 반환합니다. catch 끝에 오류 및 반환 오류가있는 경우 : 그 isDuplicate, process, insertData 가정 그리고 약속을 반환 getResposne

exports.handler = function(event, context, callback) { 

    RequestIsValid(event) 
    .then(isDuplicate) 
    .then(process) 
    .then(insertData) 
    .then(getResponse) 
    .then(function(result) { 
     //result would be the returning value of getResponse. 
     callback(null, { 
      statusCode: 200, 
      body: JSON.stringify({ 
       message: 'Done', 
       response: result 
      }) 
     }); 
    }) 
    .catch(function (error) { 
     // this will show on CloudWatch 
     console.error(
      'Error: ' + error 
     ); 
     // this will be the response for the client 
     callback({ 
      statusCode: 500, 
      body: JSON.stringify({ 
       message: error 
      }, null) 
     }); 
    }) 

// end of the function 
} 

각각의 결과는 다음에 체인 될 수있다.