简体   繁体   English

遍历AWS Lambda Nodejs SDK函数

[英]Loop through AWS Lambda Nodejs SDK function

I'm new to Nodejs and having trouble understand this issue: I tried to run a describe function against an array, and the AWS function seems to run after the main function has finished. 我是Nodejs的新手,很难理解这个问题:我试图对数组运行一个describe函数,并且AWS函数似乎在main函数完成后运行。

Here's the main function: (loop thru a list of ACM ARNs and check the status) 这是主要功能:(通过ACM ARN列表循环并检查状态)

var checkCertStatus = function(resolveObj){
    var promise = new Promise(function(resolve, reject){

        console.log('1');
        var retObj='';
        resolveObj.Items.forEach(function(element) {
            var certDescribeParams = {
                CertificateArn: element.sslCertId
            };
            console.log('2');
            acm.describeCertificate(certDescribeParams, function(err, data) {
                if(err) reject(new Error(err));
                else     {
                    console.log(data.Certificate.DomainName + ': ' + data.Certificate.Status);
                    retObj+=data;
                }
            });
        });
        console.log('3');
        resolve(retObj);
        return promise;
    })
}

Based on the debug log, assuming there are 2 items need to be processed, what I got: 基于调试日志,假设有2项需要处理,我得到了:

1
2
2
3
example.com: ISSUED
example2.com: ISSUED

Basically, I need to pass this result to the next function in the chain (with promise and stuff). 基本上,我需要将此结果传递给链中的下一个函数(带有promise和stuff)。

Welcome to Node.js! 欢迎使用Node.js! Speaking generally, it might be helpful to study up on the asynchronous programming style. 一般来说,学习异步编程风格可能会有所帮助。 In particular, you seem to be mixing Promises and callbacks , which may make this example more confusing than it needs to be. 特别是,您似乎混合了Promisescallbacks ,这可能会使此示例比需要的更加混乱。 I suggest using the AWS SDK's built-in feature to convert responses to Promises. 我建议使用AWS开发工具包的内置功能将响应转换为Promises。

The first thing I notice is that you are manually constructing a Promise with a resolve/reject function. 我注意到的第一件事是您正在手动构建带有“解决/拒绝”功能的Promise。 This is often a red flag unless you are creating a library. 除非您正在创建库,否则这通常是一个危险信号。 Most other libraries support Promises which you can simply use and chain. 其他大多数库都支持Promises,您可以简单地使用和链接。 (This includes AWS SDK, as mentioned above.) (如上所述,其中包括AWS开发工具包。)

The second thing I notice is that your checkCertStatus function does not return anything. 我注意到的第二件事是您的checkCertStatus函数不返回任何内容。 It creates a Promise but does not return it at the end. 它创建一个Promise,但最后不返回。 Your return promise; 您的return promise; line is actually inside the callback function used to create the Promise. 该行实际上位于用于创建Promise的回调函数中。

Personally, when working with Promises, I prefer to use the Bluebird library. 就个人而言,在使用Promises时,我更喜欢使用Bluebird库。 It provides more fully-featured Promises than native, including methods such as map . 它提供的功能比Promise更为完整,包括诸如map之类的方法。 Conveniently, the AWS SDK can be configured to work with an alternative Promise constructor via AWS.config.setPromisesDependency() as documented here . 方便地,可以将AWS开发工具包配置为通过AWS.config.setPromisesDependency()与替代的Promise构造函数一起使用, AWS.config.setPromisesDependency() 处所述

To simplify your logic, you might try something along these lines (untested code): 为了简化您的逻辑,您可以尝试以下方法(未经测试的代码):

const Promise = require('bluebird');
AWS.config.setPromisesDependency(Promise);

const checkCertStatus = (resolveObj) => {
    const items = resolveObj.Items;
    console.log(`Mapping ${items.length} item(s)`);
    return Promise.resolve(items)
        .map((item) => {
            const certDescribeParams = {
                CertificateArn: item.sslCertId,
            };
            console.log(`Calling describeCertificate for ${item.sslCertId}`);
            return acm.describeCertificate(certDescribeParams)
                .promise()
                .then((data) => {
                    console.log(`${data.Certificate.DomainName}: ${data.Certificate.Status}`);
                    return data;
                });
        });
};

We're defining checkCertStatus as a function which takes in resolveObj and returns a Promise chain starting from resolveObj.Items . 我们将checkCertStatus定义为一个接受resolveObj并返回从resolveObj.Items开始的Promise链的resolveObj.Items (I apologize if you are not yet familiar with Arrow Functions .) The first and only step in this chain is to map the items array to a new array of Promises returned from the acm.describeCertificate method. (如果您还不熟悉Arrow Functions,我深表歉意。)此链中的第一步也是唯一的步骤是将items数组映射到acm.describeCertificate方法返回的Promises新数组。 If any one of these individual Promises fails, the top-level Promise chain will reject as well. 如果这些个人承诺中的任何一个失败,那么顶级承诺链也会拒绝。 Otherwise, the top-level Promise chain will resolve to an array of the results. 否则,顶级Promise链将解析为一系列结果。 (Note that I included an inessential .then step just to log the individual results, but you could remove that clause entirely.) (请注意,我包括了一个不重要的.then步骤,仅用于记录各个结果,但是您可以完全删除该子句。)

Hope this helps, and I apologize if I left any mistakes in the code. 希望这会有所帮助,如果我在代码中留下任何错误,我深表歉意。

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

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