Why values are not inserted into DynamoDB unless calling `.promise()`?

倖福魔咒の 提交于 2020-05-15 09:25:29

问题


I have some simple async code in a lambda, fetching some data and then inserting that into DynamoDB.

With this code, everything works as expected:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1', apiVersion: 'latest' });

function fetchSomething() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                foo: 'Foo',
                bar: 'Bar'
            });
        }, 2000);
    })
}

exports.handler = async (event) => {
    try {
        const data = await fetchSomething();

        const params = {
            Item: {
                id: Date.now()
                ...data,
            },

            TableName: 'json'
        };

        await docClient.put(params).promise();

        console.log('Document inserted.');

        return JSON.stringify(data);
    } catch(err) {
        console.log('Something went wrong: ', err);

        return err;
    }
};

Now, if I remove the await, leaving only docClient.put(params).promise() and return a response from the lambda without waiting for DynamoDB's response, the document will still be inserted. However, if I don't call .promise() or pass it a callback instead, it won't:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1', apiVersion: 'latest' });

function fetchSomething() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                foo: 'Foo',
                bar: 'Bar'
            });
        }, 2000);
    })
}

exports.handler = async (event) => {
    try {
        const data = await fetchSomething();

        const params = {
            Item: {
                id: Date.now()
                ...data,
            },

            TableName: 'json'
        };

        // This doesn't work:
        // docClient.put(params);

        // This doesn't work either:
        // docClient.put(params, (err, data) => {
        //     if (err) throw err;
        // });

        // But this works:
        // docClient.put(params).promise();

        console.log('Inserting document...');

        return JSON.stringify(data);
    } catch(err) {
        console.log('Something went wrong: ', err);

        return err;
    }
};

Not planning to change it, but just curious about why it works like that.

来源:https://stackoverflow.com/questions/61738467/why-values-are-not-inserted-into-dynamodb-unless-calling-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!