简体   繁体   English

查询发电机数据库的 node.js function 总是返回 undefined

[英]node.js function that queries a dynamo database always returns undefined

I have the following function definition.我有以下 function 定义。 Essentially, what it does is query a DynamoDB table and return the deviceID of the corresponding partition key.本质上,它所做的是查询 DynamoDB 表并返回相应分区键的 deviceID。

GetDeviceIdFromHash: function (id) {
    const params = {
        TableName: process.env.USER_TABLE,
        Key: {
            id: id
        }
    };
    dynamoDb.get(params, function(error, result) {
        // handle potential errors
        if (error) {
            console.log(error);
            return "";
        }
        return result;
    });
}

The problem is that this function ALWAYS returns undefined , irrespectively of whether or not the id attribute is present in the database.问题是这个 function 总是返回undefined ,无论数据库中是否存在id属性。

I am not entirely sure as to why this is happening.我不完全确定为什么会这样。

Based on my hunch, I'm thinking that this might be related to dynamoDb.get() being an async statement, but my experience with node.js is limited so I don't know how to proceed.根据我的预感,我认为这可能与dynamoDb.get()作为异步语句有关,但我对 node.js 的经验有限,所以我不知道如何继续。

Caller to the function: function 的调用者:

'use strict';

const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const push = require('./helper.js')

module.exports.update = async (event, context, callback) => {
    const data = JSON.parse(event.body);
    // validation
    if (typeof data.userid !== 'string' || typeof data.restaurantid !== 'string' || typeof data.orderTime !== 'string' || typeof data.status !== 'string'
        || typeof data.confirmedtime !== 'string' || typeof data.expecteddeliverytime !== 'string' || typeof data.readytime !== 'string' || typeof data.contents !== 'string') {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t update the order',
        });
        return;
    }

    const params = {
        TableName: process.env.ORDER_TABLE,
        Key: {
            id: event.pathParameters.id,
        },
        ExpressionAttributeNames: {
            '#userid': 'userid',
            '#restaurantid': 'restaurantid',
            '#orderTime': 'orderTime',
            '#status': 'status',
            '#confirmedtime': 'confirmedtime',
            '#expecteddeliverytime': 'expecteddeliverytime',
            '#readytime': 'readytime',
            '#contents': 'contents',
        },
        ExpressionAttributeValues: {
            ':userid': data.userid,
            ':restaurantid': data.restaurantid,
            ':orderTime': data.orderTime,
            ':status': data.status,
            ':confirmedtime': data.confirmedtime,
            ':expecteddeliverytime': data.expecteddeliverytime,
            ':readytime': data.readytime,
            ':contents': data.contents
        },
        UpdateExpression: 'SET #userid = :userid, #restaurantid = :restaurantid, #orderTime = :orderTime, #status = :status, #confirmedtime = :confirmedtime, #expecteddeliverytime = :expecteddeliverytime, #readytime = :readytime, #contents = :contents',
        ReturnValues: 'ALL_NEW',
    };

    // update the address in the database
    dynamoDb.update(params, (error, result) => {
        // handle potential errors
        if (error) {
            console.error(error);
            callback(null, {
                statusCode: error.statusCode || 501,
                headers: { 'Content-Type': 'text/plain' },
                body: 'Couldn\'t update the order.'
            });
            return;
        }
        // send push notification of new order status
          var device_id = await push.GetDeviceIdFromHash(data.userid);
          var push_data = push.generatePushNotification("Order status update!", data.status);
          var res = push.sendPush(device_id, push_data);
          console.log(device_id);
          console.log(push_data);

        // create a response
        const response = {
            statusCode: 200,
            body: JSON.stringify(result.Attributes),
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true
            }
        };
        callback(null, response);
    });
};

Yeah, that might occur due to asynchronous execution.是的,这可能是由于异步执行而发生的。 So can you just try this and tell me:所以你能试试这个并告诉我:

GetDeviceIdFromHash: async function (id) {
    const params = {
        TableName: process.env.USER_TABLE,
        Key: {
            id: id
        }
    };
    let result = await dynamoDb.get(params).promise();
    return result;
}

Caller to the function: function 的调用者:

'use strict';

const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const push = require('./helper.js')

module.exports.update = async (event, context, callback) => {
    const data = JSON.parse(event.body);
    // validation
    if (typeof data.userid !== 'string' || typeof data.restaurantid !== 'string' || typeof data.orderTime !== 'string' || typeof data.status !== 'string'
        || typeof data.confirmedtime !== 'string' || typeof data.expecteddeliverytime !== 'string' || typeof data.readytime !== 'string' || typeof data.contents !== 'string') {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t update the order',
        });
        return;
    }

    const params = {
        TableName: process.env.ORDER_TABLE,
        Key: {
            id: event.pathParameters.id,
        },
        ExpressionAttributeNames: {
            '#userid': 'userid',
            '#restaurantid': 'restaurantid',
            '#orderTime': 'orderTime',
            '#status': 'status',
            '#confirmedtime': 'confirmedtime',
            '#expecteddeliverytime': 'expecteddeliverytime',
            '#readytime': 'readytime',
            '#contents': 'contents',
        },
        ExpressionAttributeValues: {
            ':userid': data.userid,
            ':restaurantid': data.restaurantid,
            ':orderTime': data.orderTime,
            ':status': data.status,
            ':confirmedtime': data.confirmedtime,
            ':expecteddeliverytime': data.expecteddeliverytime,
            ':readytime': data.readytime,
            ':contents': data.contents
        },
        UpdateExpression: 'SET #userid = :userid, #restaurantid = :restaurantid, #orderTime = :orderTime, #status = :status, #confirmedtime = :confirmedtime, #expecteddeliverytime = :expecteddeliverytime, #readytime = :readytime, #contents = :contents',
        ReturnValues: 'ALL_NEW',
    };

    // update the address in the database
    dynamoDb.update(params, (error, result) => {
        // handle potential errors
        if (error) {
            console.error(error);
            callback(null, {
                statusCode: error.statusCode || 501,
                headers: { 'Content-Type': 'text/plain' },
                body: 'Couldn\'t update the order.'
            });
            return;
        }
        // send push notification of new order status
          var device_id = await push.GetDeviceIdFromHash(data.userid);
          var push_data = push.generatePushNotification("Order status update!", data.status);
          var res = push.sendPush(device_id, push_data);
          console.log(device_id);
          console.log(push_data);

        // create a response
        const response = {
            statusCode: 200,
            body: JSON.stringify(result.Attributes),
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true
            }
        };
        callback(null, response);
    });
};

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

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