问题
I am trying to use a lambda function to alter a database and then send a push notification.
I don't want to wait for the push notification server to reply. In the occasional case that the push notification is unsuccessful, that is not a concern. It is more important that the function executes in a timely manner.
Currently I'm using the following two functions. Everything works as expected except that there doesn't seem to be any time saving. ie, when there is no device token and push is not required the function is very fast. When a push is required it is very slow. That tells me what I'm doing is wrong and the function is still waiting for a callback.
I have not used node much and know there are perils with trying to use asynchronous models from other languages. Just wondering how to overcome this case.
Function for Database Insertion:
const AWS = require('aws-sdk');
var mysql = require('mysql');
var lambda = new AWS.Lambda();
exports.handler = (event, context, callback) => {
var connection = mysql.createConnection({
host: "databaseHost",
user: "databaseUser",
password: "databasePassword",
database: "databaseName",
multipleStatements: true
});
var sql = "INSERT INTO someTable SET item_id = ?, item_name = ?"
var inserts = [event.itemId, event.itemName];
connection.query(sql, inserts, function (error, results, fields) {
connection.end();
// Handle error after the release.
if (error) {
callback(error);
} else {
if (event.userToken !== null) {
callback(null, results);
var pushPayload = { "deviceToken": event.deviceToken };
var pushParams = {
FunctionName: 'sendPushNotification',
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: JSON.stringify(pushPayload)
};
lambda.invoke(pushParams, function (err, data) {
if (err) {
context.fail(err);
} else {
context.succeed(data.Payload);
}
});
} else {
//callback(null, results);
callback(null, results);
}
}
});
};
Push notification function:
const AWS = require('aws-sdk');
var ssm = new AWS.SSM({ apiVersion: '2014-11-06' });
var apn = require("apn");
exports.handler = function (event, context) {
var options = {
token: {
key: "key",
keyId: "keyId",
teamId: "teamId"
},
production: true
};
var token = event.deviceToken;
var apnProvider = new apn.Provider(options);
var notification = new apn.Notification();
notification.alert = "message";
notification.topic = "com.example.Example";
context.callbackWaitsForEmptyEventLoop = false;
apnProvider.send(notification, [deviceToken]).then((response) => {
context.succeed(event);
});
};
回答1:
In pushParams change value of InvocationType to "Event" so that calling lambda will not wait for the response. It will just invoke lambda and return you the callback.
example:
var pushParams = {
FunctionName: 'sendPushNotification',
InvocationType: 'Event',
LogType: 'Tail',
Payload: JSON.stringify(pushPayload)
};
来源:https://stackoverflow.com/questions/50500770/node-js-and-aws-lambda-function-continue-function-execution-after-callback