Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter:

var promise = new Promise(function(resolve, reject) {
    // Perform asynchronous task
    ec2.describeInstances(function(err, data) {
        console.log("\nIn describe instances:\n");
        var list = [];
        if (err) reject(err); // handle error
        else {
            var i = 0 ;
            var reservations = data.Reservations;
            for (var i in reservations) {
                var instances = reservations[i]['Instances'];
                var j = 0;
                for (j in instances){
                    var tags = instances[j]
                    var k = 0;
                    var instanceId = tags['InstanceId'];
                    var tag = tags['Tags'];
                    var l;

                    for (l in tag){
                        if (String(tag[l]['Value']) == '2018-10-15T23:45' || String(tag[l]['Key']) == 'killdate') {
                            console.log(tag[l]['Key'] + ' ' + tag[l]['Value']);
                            list.push(instanceId);
                            console.log(list);
                        }
                    }
                }
            }       
        resolve(list);
        }
    });

});

promise.then(function (list) {
    ec2.terminateInstances(list, function(err, data) {
        if (err) console.log(err, err.stack); // handle error
        else     console.log("made it");  
    });
});

Prior to this code snippet, my initial setup was:

return new Promise(function(resolve, reject) { ... }

which worked initially. However, after making some changes by declaring it as a "var" and adding a new promise below, the functionality ceased. Specifically, neither of the two functions executed, prematurely exiting the handler without running any return statements or console logs.

I would greatly appreciate any assistance!

Thank you!

Answer №1

Questioning the feasibility of implementing code similar to this:

let promise = new Promise((resolve, reject) => {
    resolve(ec2.describeInstances...)
})

promise
    .then(/* handle successful resolution of promise */ )
    .catch(/* handle rejection of promise */ )

Answer №2

let myPromise = new Promise();

myPromise
    .then(function() {
        return ec2.describeInstances(function(error, data) {
            let instanceList = [];
            if (error) throw error; // handle errors
            // add logic here
        })
    })
    .catch(/* add error handling here if needed */)
    .then(function (instanceList) {
        return ec2.terminateInstances(instanceList, function(error, data) {
            if (error) console.log(error, error.stack); // deal with errors
            else     console.log("Successfully terminated instances");  });
    })
    .catch(/* add additional error handling here if necessary */)

Answer №3

If you want to simplify your approach, consider breaking down your logic into more manageable chunks to achieve the desired outcome.

Here's how I would suggest structuring it:

Create a promise function for your service:

function myAsyncFunction(url) {
    return new Promise((resolve, reject) => {
        success = () => resolve(data);
        failure = () => reject(err);
    });
}

Next, handle your promise with a caller function:

myAsyncFunction().then(dataHandler(result), // "Promise fulfilled!"
    function (err) {// Error: "It failed"
        console.log(err)
    });

Finally, implement the main logic:

function dataHandler(data) { /* Logic for handling data */}

Best of luck with your implementation!

Answer №4

After resolving the issue, I forgot to update before incorporating the SNS portion. During this process, I gained valuable knowledge about functional programming and decided to use the await function instead of the intricate promise syntax. Here is the revised code snippet:

exports.handler = async (event, result, callback) => {

    const AWS  = require('aws-sdk');
    const date = new Date().toISOString().substr(0, 16)
    const ec2  = new AWS.EC2();
    var sns = new AWS.SNS();

    console.log("date is: " + date)
    console.log(date.length);

    const params = {
            TopicArn:'arn:aws:sns:us-east-1:503782973686:test',
            Message:'Success!!! ',
            Subject: 'TestSNS'
        }

    const describeResult = await ec2.describeInstances().promise()

    const terminatableInstances = await describeResult
        .Reservations
        .reduce((acc, reservation) => acc.concat(reservation.Instances), [])
        //'2018-10-15T23:45'
        .map((instance) => {
            //console.log(instance)
            //console.log(instance.Tags)
            var date = instance.Tags
            .filter(tag => tag.Key == 'killdate' && tag.Value == date) //date should be in this format on tag: 2018-10-15T23:45
            .reduce((acc, curr) => curr.Value, null);
            if (date != null) {
                return instance.InstanceId;
            }
            return null;
        })
        .filter(id  => id != null)


    console.log(terminatableInstances);

    const snsPush = await ec2.terminateInstances({
        InstanceIds: terminatableInstances,
        //DryRun: true //set this flag if you want to do a dry run without terming instances
    }, (err, data) => {

        if (err) {
            console.log('no instances to terminate!')
        }
        else {
            console.log('terminated instances')
        }

    })

    console.log(snsPush)
    //return(snsPush).promise()
    return sns.publish(params, (err, data) => {
        if (err) {
            console.log(err, err.stack); 
        }
        else {
             console.log('sent');
        }
        }).promise(); 


};

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

Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the this.http.post('http://localhost:8000/login', body, { h ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

In the Opera browser, the closing script tags seem to mysteriously vanish

I recently built a website using bootstrap and implemented the JQuery load function to merge separate HTML files into one for better organization. The site is currently live on github pages. However, I've encountered an issue specifically with Opera ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Creating a CSV download feature with ReactJS is simple and incredibly useful. Enable users

Despite searching through various posts on this topic, I have yet to find a solution that addresses my specific issue. I've experimented with different libraries and combinations of them in an attempt to achieve the desired outcome, but so far, I have ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

Change the background of the play/stop icon with a jquery toggle

There is a list of video links with play icons as backgrounds in front of them. When a user clicks on a link, the video will start playing in a player located to the left of the links. The clicked link's background icon changes to a 'stop' i ...

Utilizing vuex methods within a promise

I'm having trouble grasping this conceptually. In my attempt to utilize a Vuex store action within a second .then() function of a promise ( this.$store.dispatch('setAdditionalUserInfo', doc.data())) , I encountered the error message: TypeEr ...

The search function for selecting plugins is not functioning properly when additional options are added

Is there a way to use select options with search functionality, but the options are appended? I've tried using plugins like tom-select, selectize, and chosen but none of them seem to work with the appended options. Can anyone provide assistance on how ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

What are the steps for implementing this javascript code in an HTML document?

Recently, I've been seeking advice on how to address the issue of wanting a button click to automatically select the search box on my website. Suggestions have pointed towards using Javascript for this functionality, with the following code recommend ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

Avoid displaying passwords in source code

Currently, I am working on developing a password manager web application similar to LastPass. One issue that has come to my attention is the visibility of variables containing decrypted passwords in the source code after retrieving them from a database u ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

There is an issue showing up in the console: $(…).datepicker is not defined as a function

I am new to using HTML with JavaScript. I attempted to implement a datepicker, but unfortunately, it is not working as expected. The error message I am receiving is '$(...).datepicker is not a function' in the console. I am utilizing multiple f ...

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...