简体   繁体   English

将函数作为参数传递时的承诺

[英]Promises when passing a function as a parameter

I understand how promises work for the most part, but I have a lot of trouble understanding how to deal with them when I need to pass a function as a parameter: 我了解了Promise的大部分工作原理,但是当我需要将函数作为参数传递时,我很难理解如何处理它们:

var promise = new Promise(function(resolve, reject) {
    // Do async job
    ec2.describeInstances(function(err, data) {
        console.log("\nIn describe instances:\n");
        var list = [];
        if (err) reject(err); // an error occurred
        else {
            var i = 0 ;
            //console.log(data.Reservations);
            var reservations = data.Reservations;
            for (var i in reservations) {
                var instances = reservations[i]['Instances'];
                var j = 0;
                //console.log(JSON.stringify(instances, null, 2));
                for (j in instances){
                    var tags = instances[j]
                    var k = 0;
                    var instanceId = tags['InstanceId'];
                    var tag = tags['Tags'];
                    var l;
                    //console.log(tag);

                    for (l in tag){
                        //console.log(instanceId);
                        //console.log(tag[l]['Value']);
                        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);

                            //return(list);
                        }
                    }
                }
            }       
        resolve(list);
        }
    });

});

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

before I had the first part of the code as: 在我将代码的第一部分设为:

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

and that worked for the first part, but as soon as I changed it to a "var" and added the new promise in underneath, it stopped working. 并在第一部分中起作用,但是当我将其更改为“ var”并在下面添加新的诺言后,它就停止了工作。 (edit) When I mean "stopped working" I mean, neither of the two functions run, ie: it ends the handler before either functions are finished and none of the return statements or console logs. (编辑)我的意思是“停止工作”,这两个函数均未运行,即:它在两个函数中的任何一个完成之前都结束了处理程序,并且没有return语句或控制台日志。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Thanks! 谢谢!

Wondering if something like this would work: 想知道这样的事情是否可行:

var promise = Promise.resolve(function() {
    return ec2.describeInstances...
})

promise
    .then(/* handle successful promise resolution */ )
    .catch(/* handle promise rejection */ )
var promise = Promise.resolve();

promise
    .then(function() {
        return ec2.describeInstances(function(err, data) {
            var list = [];
            if (err) throw err; // an error occurred
            // else logic
        })
    })
    .catch(/* if needed here */)
    .then(function (list) {
        return ec2.terminateInstances(list, function(err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else     console.log("made it");  });
    })
    .catch(/* if needed here */)

my suggestion is to break up your logic - it will be easier to handle the result you want to achieve. 我的建议是破坏您的逻辑-处理您想要获得的结果会更容易。

A proper way in my opinion: 我认为正确的方法是:

promise function(a service function): 承诺函数(服务函数):

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

then your promise caller: 然后您的答应者:

myAsyncFunction().then(dataHandler(result), // "promise worked!"
    function (err) {// Error: "It broke"
        console.log(err)
    });

then the logic: 那么逻辑:

    function dataHandler(data) { /* data logic */}

good luck 祝好运

I ended up fixing it. 我最终解决了它。 Sorry, forgot to post back before I added in the SNS portion. 抱歉,在添加SNS部分之前忘了发回邮件。 I ended up learning a ton about functional programming on the way and decided to use the await function over the complicated promise syntax. 我最终在此途中学习了大量有关函数式编程的知识,并决定在复杂的promise语法上使用await函数。 Below is the code: 下面是代码:

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


};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM