问题
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