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

Can you provide the regular expression that will successfully match this specific string of text?

Can you solve this fruit riddle? apple is 2kg apple banana mango is 2kg apple apple apple is 6kg banana banana banana is 6kg If the fruits are limited to "apple", "banana", and "mango", how can we write a regex that extracts the names of ...

One array comprises of all elements found in a separate array

After grappling with this problem for a while, I still haven't been able to find a solution. If I have 2 arrays structured like this: array1 = [ { name: 'John', age : 25}, { name: 'Jane', age : 58} ] array2 = [ { name: ...

Transitioning from curl to jQuery's $.ajax() method

Recently, I encountered a challenge while trying to switch the curl code used for an API known as TextRazor to jquery's AJAX due to certain limitations on the platform. Despite exploring various solutions suggested by the community in response to simi ...

Guidance on calling a JavaScript function from a dynamically added control

The Master page includes a ScriptManager. Next, I have a Control with a ScriptManagerProxy and an UpdatePanel. Within the UpdatePanel, I dynamically insert another Control (which also has a ScriptManagerProxy) that needs to run some JavaScript code. In ...

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...

Having trouble getting the map function to work in ReactJs while using Next.js?

Hey there, I am diving into ReactJS with the "Nextjs" framework and working on fetching data using async functions. However, I am facing an issue where I am unable to fetch data using the map function. The console.log is displaying a message saying "item ...

Why isn't this code for hiding the animation and displaying it not functioning properly?

Why isn't this animation from display none to block working properly? The initial code appears as follows, and it functions correctly: $(".box_outer").stop().animate({top: '25px' , opacity: 1}, 100); When I add display: none; to the class ...

Is there a way to retrieve the value from a moment-formatted date picker in the (YYYY-MM-DD) format?

I have a Vue application with a datepicker from Ant Design Vue that is returning the following moment object: Moment {…} _d: Thu Oct 24 1996 00:00:00 GMT+0800 (Malaysia Time) _f: "YYYY-MM-DD" _i: "1996-10-15" _isAMomentObject: (...) _isUTC: (...) _isVal ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Angular debounce on checkboxes allows you to prevent multiple rapid changes from

Managing multiple checkboxes to filter a dataset can be tricky. I am looking for a way to debounce the checkbox selection so that the filter is only triggered after a certain period of time, like waiting 500ms to a second after the last checkbox has been c ...

Leveraging arrays generated from two separate MySQL queries for dual selection functionality with JavaScript

I have successfully populated the first HTML select with results from the first query. Now, I would like to store the results from the second query in either a Json file or XML and then use plain javascript (not jQuery) to populate the second HTML select ...

What is the process for pulling out a specific JSON element based on a condition?

I am working with a JSON object that looks like this: "links" : [ { "rel" : "first", "href" : "http://localhost:8080/first" }, { "rel" : "self", "href" : "http://localhost:8080/self" }, { "rel" : "next", "href" : "http://loca ...

What is the best way to send a form using ajax?

I am having trouble submitting forms without a post back using AJAX. My code is not working as expected. What could be the issue in my script? I am new to AJAX and would appreciate some help with AJAX scripts. Below you can find my code: Please note: I ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Determine if two arrays of objects in JavaScript are equal and if so, store any new items in MongoDB

Hey there! I'm in the process of comparing two arrays of objects, each object containing an ID. One array is sourced from Stripe, while the other is retrieved from my database. The goal is to determine if the IDs match - returning true when they do an ...

Trouble with Metro UI Library: CSS not loading properly

I am having trouble with the navbar CSS on my website while using the Metro UI CSS library. Check out my HTML code: <!DOCTYPE html> <html lang="en"> <head> <title>TelePrint Blog</title> <link rel="stylesheet" href= ...

the absence of any content being shown when using v-else

I'm currently delving into Vue.js and stumbled upon an unusual behavior that I couldn't find any information about on the Internet. For some reason, the DIV with v-else isn't rendering any content that I place inside it. I tried to underst ...

Issues with triggering express.js app.post middleware

Logging to the console: app.use(function (req, res, next) { console.log(req.method) console.log('why is it not working?') }) However, the following code does not log anything: app.post(function (req, res, next) { console.l ...

Utilizing Express.js: Implementing a Route that is Outside the Current Router

app.js: var app = express(); app.use('/my-page', require('./routes/my-page.js')); my-page.js: const router = require('express').Router(); router.get('/one', function (req, res, next) { return res.send('thi ...