Node.js会在回调后继续执行语句吗?

时间:2018-04-01 12:30:06

标签: node.js asynchronous callback

我在lambda函数中使用node.js将数据保存到mysql数据库,然后发送推送通知。我希望在保存到数据库之后和发送推送通知以获得性能之前进行回调。但我希望推送代码在回调后继续执行。

这就是我所拥有的:

const AWS = require('aws-sdk');
var mysql = require('mysql');
var apn = require("apn");

exports.handler = (event, context, callback) => {

    var connection = mysql.createConnection({
        host: "databaseHost",
        user: "databaseUser",
        password: "databasePassword",
        database: "databaseName",
    });

    var sql = "INSERT INTO some_table SET some_id = ?";
    var inserts = [event.someId];

    connection.query(sql, inserts, function (error, results, fields) {
        connection.end();
        if (error) {
            callback(error);
        } else {
            var options = {
                token: {
                    key: "key.p8",
                    keyId: "keyId",
                    teamId: "teamId"
                },
                production: true
            };
            var message = "Some Message";
            var apnProvider = new apn.Provider(options);

            var deviceTokens = event.deviceTokenArray;

            var notification = new apn.Notification();
            notification.alert = message;

            notification.topic = "com.example.example";

            apnProvider.send(notification, deviceTokens).then((response) => {
                callback(null, event.arguments.input);
            });
        }
    });
};

我想要的是让apnProvider函数中的回调在该函数之前发生,但该函数继续执行。理想情况下,我希望将推送消息放在一个单独的文件中,但我想这是一个不同的问题,我稍后会解决。

1 个答案:

答案 0 :(得分:2)

可能或可能不是良好的做法,但它完全可行。只需回调并执行其余代码即可。

const AWS = require('aws-sdk');
var mysql = require('mysql');
var apn = require("apn");

exports.handler = (event, context, callback) => {

    var connection = mysql.createConnection({ /* .. */ });

    var sql = "INSERT INTO some_table SET some_id = ?";
    var inserts = [event.someId];

    connection.query(sql, inserts, function (error, results, fields) {
        connection.end();
        if (error) {
            callback(error);
        } else {
            callback(null, event.arguments.input);

            // consider moving this out to a separate lambda, the
            // function is essentially done
            var options = { /*  */ };
            var message = "Some Message";
            var apnProvider = new apn.Provider(options);

            var deviceTokens = event.deviceTokenArray;

            var notification = new apn.Notification();
            notification.alert = message;

            notification.topic = "com.example.example";

            apnProvider.send(notification, deviceTokens).then((response) => {
              console.log('log response here');
            });
        }
    });
};

理想情况下,你最有可能想要分割你的lambdas,这样他们就不会做太多。也许有一个lambda 只是查询数据库,另一个发出通知,另一个持有一些数据等。