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

时间:2018-10-16 17:32:25

标签: javascript function parameters 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");  });
});

在我将代码的第一部分设为:

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

并在第一部分中起作用,但是当我将其更改为“ var”并在下面添加新的诺言后,它便停止工作。 (编辑)我的意思是“停止工作”是指这两个函数均未运行,即:它在两个函数中的任何一个完成之前都结束了处理程序,并且没有return语句或控制台日志。

任何帮助将不胜感激!

谢谢!

4 个答案:

答案 0 :(得分:1)

想知道这样的事情是否可行:

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

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

答案 1 :(得分:1)

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 */)

答案 2 :(得分:0)

我的建议是破坏您的逻辑-处理您想要获得的结果会更容易。

我认为正确的方法:

承诺功能(服务功能)

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

然后您的诺言呼叫者:

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

然后是逻辑:

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

祝你好运

答案 3 :(得分:0)

我最终修复了它。抱歉,在添加SNS部分之前忘了发回邮件。我最终在此途中学习了大量有关函数式编程的知识,并决定在复杂的promise语法上使用await函数。下面是代码:

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


};