2017-09-28 5 views
0

私は約束の成功/失敗を出力しようと苦労しています。AWSラムダハンドラ内のコールバックを使用

私は約束の内側の成功に失敗し、Q.defer.resolve(success_message)にを呼び出しています一緒にこの

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' 
       }) 
      }); 
     }); 
    }); 
}; 

のような約束をチェーン化しています。これらの約束のいずれかが失敗すると、エラーは.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 Gatewayを使用していると思われます。とにかく、すべての関数を矢印関数で置き換えてみましょう。 –

+2

質問をクリアしてください。 まず、エラーが発生しても 'null'値でコールバックを呼び出す理由は何ですか? 実際には、関数の現在の動作は何ですか?タイムアウトや何かによってのみ終了しますか? –

+0

@ArtemArkhipov私は約束を使用するときにコールバック関数の使用を正しく知りたい。私はこれを更新しました。私はラムダにこのコールバックを返すだけで、どのパラメータが使用されても問題ではないという印象を受けました。私は彼らが違う行為をしていることに気づいていませんでした。 –

答えて

0

Chain your promises all the way you usually do it、ありがとうございました。チェーンの最後のステップで結果を返します。 catch最後のエラー、およびもしあればエラーを返す:

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 
} 

isDuplicateprocessinsertDatagetResposneを約束し、次のいずれかに連鎖させることができ、それぞれの結果を返すことを想定しています。

関連する問題