Struggling to get your function to complete its execution due to asynchronous operations?

The code in the comment block is not functioning properly when placed inside an if statement.

It seems that the issue may be related to its position before a return statement, so I am looking for a way to ensure it completes running before the return is called.

I have attempted using let {cool} = await .... but have had no success.

The goal is to simply copy and paste the code snippet from above into the if statement.

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

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

  let Payload = JSON.stringify(PayloadObj);
  let params = {
    FunctionName: "lambda-2", // the lambda function we are invoking
    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");

  let amount = event["amount"];
  let 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;
  }
};

Answer №1

When using the await keyword, there is no need for a callback function to handle data and errors. Instead, you can use a try-catch block as shown below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

What are some ways to enable multi-threading in NodeJS?

Is there a way to transform NodeJS from a single threaded asynchronous language into a multi-threaded one? ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

AWS Lambda optimizes variable initialization by reusing values from previous executions, eliminating the need to reinitialize

Currently, I am encountering a problem while deploying an AWS Lambda Function for numeric calculations. The issue arises when the function is initially deployed and runs correctly, but subsequently it starts taking previous values into account and recalcul ...

JavaScript - Unable to unselect a button without triggering a page refresh

I have a series of buttons in a row that I can select individually. However, I only want to be able to choose one button at a time. Every time I deselect the previously selected button, it causes the page to reload when all I really want is for all the but ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Guide on how to incorporate an external javascript file into an HTML button

I am currently working on an exercise through Udacity that involves creating an HTML form with JavaScript functions. The task is to input text into the form, submit it, and have it displayed on the webpage within a blue square. This exercise is designed to ...

jQuery auto-suggest feature failing to display search results

Just to clarify, I have very little experience with JS, so my understanding is limited. Fair warning :-) I'm currently working on an autocomplete menu that retrieves data from a webservice. This webservice will return various types of elements (such ...

Problem: Implementing a horizontal scrolling feature using Skrollr

I'm interested in creating a horizontal animation controlled by skrollr. As I scroll down, I want the elements on my page to move from left to right within my container. When all elements have the same width, setting the scrolling data from 100% to 0 ...

JavaScript code for computing the error function of Gauss

Are there any freely available implementations of the Gauss error function in JavaScript under a BSD or MIT license? ...

Identify specific terms within a webpage using an iframe that is integrated onto the same page

Is there a way to implement word highlighting on a webpage containing an iframe with a search field? The concept involves allowing a user to input search terms within the iframe, which would then send a command to highlight those words on the main page. ...

Adjust the appearance of an element in a different parent when hovering over a specific element with a matching index

I have implemented a menu on my site in two different ways - one using text and the other using pictures. Users can click on both types of menus. Now, I am looking to create an interactive feature where hovering over a specific item in the text menu (such ...

Load the entire AngularJS webpage using AJAX requests

I'm facing a challenge where I need to integrate an entire legacy page, along with some AngularJS elements, into our new page using AJAX. Initially, all I could see was the raw AngularJS markup: Rank ID {{$index+1}} {{player.playerid}} Afte ...

Utilizing React: passing a Component as a prop and enhancing it with additional properties

My question involves a versatile component setup like the one below const Img = ({ component }) => { const image_ref = useRef() return ( <> {component ref={image_ref} } </> ) } I am exploring ways to use this compo ...

The constant reloading of localhost is due to the connection of Mongodb with Node.js

I am facing an issue while trying to establish a connection between my Node.js Express script and the backend MongoDB 5.0.5. When I run the app.js using nodemon, it shows that the MongoDB is connected; however, on the localhost, the page keeps reloading wi ...

I am unable to employ the useMutation or useQuery features in Apollo Client 3.0

import { useMutation } from '@apollo/client';; function LockedBlog() { const [lockedBlog] = useMutation(LOCKED_BLOG); }; class EditBlog extends Component { state = { ...initialState }; index.js import React from "react"; im ...

Execute a function multiple times within a loop

My task involves passing objects from an array to a function one at a time with a 1-second pause in between each item: async function CallingLabels() { if(id) { if(LabelNumbers) { LabelNumbers.forEach(async (Label) => { await ...

Incorporating the Microsoft Teams Embedded Share Button within a React-based web application

Recently, I successfully implemented the Microsoft Teams Embedded Share Button in React by following these steps: Step 1: First, I included the launcher.js script on my web app: I simply added this script to a useEffect hook: <script async defer src=& ...

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...