代码之家  ›  专栏  ›  技术社区  ›  Back2Basics

如何在javascript中向lambda添加“.then()”和“.catch()”

  •  -1
  • Back2Basics  · 技术社区  · 4 年前

    我正在寻找在功能上做这样的东西。这个例子的问题是从此以后的.then()语句(语法问题)。我该如何用“then”和“catch”部分发出lambda?

    const AWS = require("aws-sdk");
    const lambda = new AWS.Lambda({
        region: "us-west-2"
    });
    exports.my_func = async function(email) {
    
        const params = {
            FunctionName: funcion_name,
            InvocationType: 'RequestResponse',
            LogType: 'Tail',
            Payload: JSON.stringify(email)
        };
    
    
        lambda.invoke(params)
            .then(response => {
                const thing = other_function(response)
                return thing
            })
            .catch(err => {
                throw my_error(400, 'Not working '+ err);
            })
    }
    
    1 回复  |  直到 4 年前
        1
  •  3
  •   hgb123    4 年前

    你可以使用 .promise()

    const lambdaInvokePromise = params => lambda.invoke(params).promise()
    
    // ...
    
    lambdaInvokePromise(params)
      .then(response => {
        const thing = other_function(response)
        return thing
      })
      .catch(err => {
        throw my_error(400, 'Not working ' + err)
      })
    
    const AWS = require('aws-sdk')
    const lambda = new AWS.Lambda({
      region: 'us-west-2'
    })
    
    const lambdaInvokePromise = params => lambda.invoke(params).promise()
    
    exports.my_func = async function(email) {
      const params = {
        FunctionName: funcion_name,
        InvocationType: 'RequestResponse',
        LogType: 'Tail',
        Payload: JSON.stringify(email)
      }
    
      lambdaInvokePromise(params)
        .then(response => {
          const thing = other_function(response)
          return thing
        })
        .catch(err => {
          throw my_error(400, 'Not working ' + err)
        })
    }
    
    

    参考资料

    Using Javascript Promise - AWS SDK for Javascript

        2
  •  2
  •   Edward Romero    4 年前

    你不需要使用then/catch。你可以使用@hgb123中提到的promise,但我会稍微更改代码以使用async/await,因为你已经在一个async函数中了。

    try {
        const response = await lambda.invoke(params).promise();
        return other_function(response)
    } catch(e) {
        throw my_error(400, 'Not working '+ err);
    }