由于异步功能未完成的问题?

时间:2020-04-15 22:24:44

标签: javascript asynchronous aws-lambda async-await

如果我将其放在if语句中,则注释块中的代码将无法正常工作。

我认为主要的问题是它恰好在return语句之前,因此如何确保它在启动return之前完成运行。

我尝试let {cool} = await ....并没有运气

目的是将代码从上方复制并粘贴到if语句内部。

var AWS = require("aws-sdk");
AWS.config.region = "us-east-1";
var lambda = new AWS.Lambda();

exports.handler = async (event) => {
  ////----------------------------THIS CODE HERE WORKS-------------------------------------------///////
  var PayloadObj = {
    amount: String(event["amount"]),
    email: String(event["email"]),
  };

  var Payload = JSON.stringify(PayloadObj);
  var params = {
    FunctionName: "lambda-2", // the lambda function we are going to invoke
    Payload: Payload,
  };
  let { cool } = lambda.invoke(params, function (err, data) {
    if (err) {
      console.log(err);
    } else {
      console.log(data.Payload);
    }
  });

  //-------------------------------------END of this CODE --------------------------------------////

  // TODO implement

  const stripe = require("stripe")("sk_test");

  var amount = event["amount"];
  var token = event["token"];

  let { status } = await stripe.charges.create({
    amount: amount * 100,
    currency: "usd",
    description: amount,
    source: token,
  });

  if (status === "succeeded") {
    //--------------------------------Same code here!-------------------------------///
    // same code from above
    //---------------------------Does not work!!------------------------------------------//

    const response = {
      statusCode: 200,
      body: JSON.stringify(status),
    };
    return response;
  } else {
    const response = {
      statusCode: 402,
      body: JSON.stringify("Payment Failed"),
    };
    return response;
  }
};

1 个答案:

答案 0 :(得分:1)

如果您使用的是等待,则不需要使用回调功能来显示数据和错误。您可以只使用try-catch块。

var PayloadObj = {
  amount: String(event["amount"]),
  email: String(event["email"]),
};

var Payload = JSON.stringify(PayloadObj);
var params = {
  FunctionName: "lambda-2", // the lambda function we are going to invoke
  InvocationType: "RequestResponse", // InvocationType: "Event",
  Payload: Payload,
};

try{
  const data = await lambda.invoke(params).promise();
  console.log(data.payload);
}catch(err){
  console.log(err);
}