最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

NodeJS Lambda函数无法正常遍历记录

IT培训 admin 13浏览 0评论

NodeJS Lambda函数无法正常遍历记录

我正在设置Lambda函数,该函数将从SQS队列中获取记录,调用API,获取信息,然后将该信息保存在RDS中。出于某种原因,当我遍历记录并进行https请求和mySQL保存时,它不会触发该逻辑。我将控制台日志遍历整个循环,并在https请求之前触发了第一个控制台日志,仅此而已。如果我删除任何解析或返回该脚本实际上会触发,请遍历所有消息,但超时。

我尝试使用诺言。我试图使函数异步,但是由于某种原因,它只是跳过了结尾,根本不更新数据库。

exports.handler = function(event, context) {

    return new Promise((resolve, reject) => {
        event.Records.forEach(record => {

            const { body } = record
            var receiptHandle = record.receiptHandle;
            var JobNumber = body
            var newJobNumber = JobNumber.replace(/['"]+/g, '');

            console.log(JobNumber);

            var optionsSchedule = {
                host: "api.myteamsoftware",
                path: "/WinTeam/Jobs/v2/api/Jobs/" + newJobNumber + "/PersonnelSchedules",
                port: 443,
                method: process.env.requestType,
                headers: {
                    'TenantId': process.env.tenantId,
                    'Ocp-Apim-Subscription-Key': process.env.ocpApimSubscriptionKey,
                    'DateFrom': dateFormat(new Date(), "yyyy-mm-dd"),
                    'DateTo': dateFormat(new Date(), "yyyy-mm-dd")
                }
            };

            console.log('After options set')

            const req = https.request(optionsSchedule, (resSchedule) => {

                if (resSchedule.statusCode < 200 || resSchedule.statusCode >= 300) {
                    return new Error('statusCode=' + resSchedule.statusCode);
                }

                var bodySchedule = [];

                resSchedule.on('data', function(chunk) {
                    bodySchedule.push(chunk);
                });

                resSchedule.on('end', function() {
                    try {

                        //Has to be turned into string in order to PARSE IT
                        bodySchedule = JSON.parse(Buffer.concat(bodySchedule).toString());

                    }
                    catch (e) {
                        return e;
                    }

                    for (var i = 0; i < bodySchedule.length; i++) {

                        values.push([
                            bodySchedule[i].Id,
                            bodySchedule[i].JobNumber,
                            bodySchedule[i].EmployeeNumber,
                            bodySchedule[i].JobPostDetailID,
                            bodySchedule[i].WorkDate,
                            bodySchedule[i].InTime,
                            bodySchedule[i].OutTime,
                            bodySchedule[i].Hours,
                            bodySchedule[i].Lunch,
                            new Date().toISOString()
                        ]);

                    }

                    connection.query(insertQuery + updateQuery, [values], function(err, result) {
                        if (err) throw err;
                        console.log(result);
                    });

                });

            });

            console.log('After request')

            req.on('error', (e) => {
                return e.message;
            })

            req.end();

            var sqs = new AWS.SQS();

            sqs.deleteMessage({
                QueueUrl: ‘xxxxxx’,
                ReceiptHandle: receiptHandle
            });

        });

    }).then(function() {
        console.log('Then')
        connection.query(insertQuery + updateQuery, [values], function(err, result) {
            if (err) throw err;
            console.log(result);
        });
        return 'Then done';
    });

};

它处理上面的代码,更新数据库,然后超时。这是日志:

START RequestId: 54f63e46-3da8-46b5-b786-a2168b456626 Version: $LATEST
2019-06-30T16:40:06.724Z    54f63e46-3da8-46b5-b786-a2168b456626    100900
2019-06-30T16:40:06.725Z    54f63e46-3da8-46b5-b786-a2168b456626    After options set
2019-06-30T16:40:06.737Z    54f63e46-3da8-46b5-b786-a2168b456626    After request
2019-06-30T16:40:06.743Z    54f63e46-3da8-46b5-b786-a2168b456626    999248
2019-06-30T16:40:06.743Z    54f63e46-3da8-46b5-b786-a2168b456626    After options set
2019-06-30T16:40:06.744Z    54f63e46-3da8-46b5-b786-a2168b456626    After request
2019-06-30T16:40:07.192Z    54f63e46-3da8-46b5-b786-a2168b456626    OkPacket {
  fieldCount: 0,
  affectedRows: 26,
  insertId: 0,
  serverStatus: 2,
  warningCount: 13,
  message: '(Records: 13  Duplicates: 0  Warnings: 13',
  protocol41: true,
  changedRows: 0 }
2019-06-30T16:40:07.203Z    54f63e46-3da8-46b5-b786-a2168b456626    OkPacket {
  fieldCount: 0,
  affectedRows: 25,
  insertId: 0,
  serverStatus: 2,
  warningCount: 19,
  message: ')Records: 19  Duplicates: 13  Warnings: 19',
  protocol41: true,
  changedRows: 13 }
END RequestId: 54f63e46-3da8-46b5-b786-a2168b456626
REPORT RequestId: 54f63e46-3da8-46b5-b786-a2168b456626  Duration: 24024.24 ms   Billed Duration: 24000 ms   Memory Size: 1536 MB    Max Memory Used: 35 MB  
2019-06-30T16:40:30.746Z 54f63e46-3da8-46b5-b786-a2168b456626 Task timed out after 24.02 seconds
回答如下:

您需要在promise块中的某个位置解析或拒绝,才能继续到下一个then()或catch():

return new Promise((resolve, reject) => {
    ... something good happens ...
    return resolve();
    ... something bad happens ...
    return reject();
}).then(function() {
    ... after something good happens ...
}).catch(function() {
    ... after something bad happens ...
});

NodeJS Lambda函数无法正常遍历记录

我正在设置Lambda函数,该函数将从SQS队列中获取记录,调用API,获取信息,然后将该信息保存在RDS中。出于某种原因,当我遍历记录并进行https请求和mySQL保存时,它不会触发该逻辑。我将控制台日志遍历整个循环,并在https请求之前触发了第一个控制台日志,仅此而已。如果我删除任何解析或返回该脚本实际上会触发,请遍历所有消息,但超时。

我尝试使用诺言。我试图使函数异步,但是由于某种原因,它只是跳过了结尾,根本不更新数据库。

exports.handler = function(event, context) {

    return new Promise((resolve, reject) => {
        event.Records.forEach(record => {

            const { body } = record
            var receiptHandle = record.receiptHandle;
            var JobNumber = body
            var newJobNumber = JobNumber.replace(/['"]+/g, '');

            console.log(JobNumber);

            var optionsSchedule = {
                host: "api.myteamsoftware",
                path: "/WinTeam/Jobs/v2/api/Jobs/" + newJobNumber + "/PersonnelSchedules",
                port: 443,
                method: process.env.requestType,
                headers: {
                    'TenantId': process.env.tenantId,
                    'Ocp-Apim-Subscription-Key': process.env.ocpApimSubscriptionKey,
                    'DateFrom': dateFormat(new Date(), "yyyy-mm-dd"),
                    'DateTo': dateFormat(new Date(), "yyyy-mm-dd")
                }
            };

            console.log('After options set')

            const req = https.request(optionsSchedule, (resSchedule) => {

                if (resSchedule.statusCode < 200 || resSchedule.statusCode >= 300) {
                    return new Error('statusCode=' + resSchedule.statusCode);
                }

                var bodySchedule = [];

                resSchedule.on('data', function(chunk) {
                    bodySchedule.push(chunk);
                });

                resSchedule.on('end', function() {
                    try {

                        //Has to be turned into string in order to PARSE IT
                        bodySchedule = JSON.parse(Buffer.concat(bodySchedule).toString());

                    }
                    catch (e) {
                        return e;
                    }

                    for (var i = 0; i < bodySchedule.length; i++) {

                        values.push([
                            bodySchedule[i].Id,
                            bodySchedule[i].JobNumber,
                            bodySchedule[i].EmployeeNumber,
                            bodySchedule[i].JobPostDetailID,
                            bodySchedule[i].WorkDate,
                            bodySchedule[i].InTime,
                            bodySchedule[i].OutTime,
                            bodySchedule[i].Hours,
                            bodySchedule[i].Lunch,
                            new Date().toISOString()
                        ]);

                    }

                    connection.query(insertQuery + updateQuery, [values], function(err, result) {
                        if (err) throw err;
                        console.log(result);
                    });

                });

            });

            console.log('After request')

            req.on('error', (e) => {
                return e.message;
            })

            req.end();

            var sqs = new AWS.SQS();

            sqs.deleteMessage({
                QueueUrl: ‘xxxxxx’,
                ReceiptHandle: receiptHandle
            });

        });

    }).then(function() {
        console.log('Then')
        connection.query(insertQuery + updateQuery, [values], function(err, result) {
            if (err) throw err;
            console.log(result);
        });
        return 'Then done';
    });

};

它处理上面的代码,更新数据库,然后超时。这是日志:

START RequestId: 54f63e46-3da8-46b5-b786-a2168b456626 Version: $LATEST
2019-06-30T16:40:06.724Z    54f63e46-3da8-46b5-b786-a2168b456626    100900
2019-06-30T16:40:06.725Z    54f63e46-3da8-46b5-b786-a2168b456626    After options set
2019-06-30T16:40:06.737Z    54f63e46-3da8-46b5-b786-a2168b456626    After request
2019-06-30T16:40:06.743Z    54f63e46-3da8-46b5-b786-a2168b456626    999248
2019-06-30T16:40:06.743Z    54f63e46-3da8-46b5-b786-a2168b456626    After options set
2019-06-30T16:40:06.744Z    54f63e46-3da8-46b5-b786-a2168b456626    After request
2019-06-30T16:40:07.192Z    54f63e46-3da8-46b5-b786-a2168b456626    OkPacket {
  fieldCount: 0,
  affectedRows: 26,
  insertId: 0,
  serverStatus: 2,
  warningCount: 13,
  message: '(Records: 13  Duplicates: 0  Warnings: 13',
  protocol41: true,
  changedRows: 0 }
2019-06-30T16:40:07.203Z    54f63e46-3da8-46b5-b786-a2168b456626    OkPacket {
  fieldCount: 0,
  affectedRows: 25,
  insertId: 0,
  serverStatus: 2,
  warningCount: 19,
  message: ')Records: 19  Duplicates: 13  Warnings: 19',
  protocol41: true,
  changedRows: 13 }
END RequestId: 54f63e46-3da8-46b5-b786-a2168b456626
REPORT RequestId: 54f63e46-3da8-46b5-b786-a2168b456626  Duration: 24024.24 ms   Billed Duration: 24000 ms   Memory Size: 1536 MB    Max Memory Used: 35 MB  
2019-06-30T16:40:30.746Z 54f63e46-3da8-46b5-b786-a2168b456626 Task timed out after 24.02 seconds
回答如下:

您需要在promise块中的某个位置解析或拒绝,才能继续到下一个then()或catch():

return new Promise((resolve, reject) => {
    ... something good happens ...
    return resolve();
    ... something bad happens ...
    return reject();
}).then(function() {
    ... after something good happens ...
}).catch(function() {
    ... after something bad happens ...
});
发布评论

评论列表 (0)

  1. 暂无评论