Reputation: 835
I'm trying to execute two asynchronous functions to DynamoDB.
I will need the return data from both before continuing with the following step which is sending an email that contains their data.
How do I tackle this issue?
I'm using the following code:
var productParams = {
TableName: productsTable,
FilterExpression: 'client = :this_client',
ExpressionAttributeValues: { ':this_client': "someclient" }
};
dynamoClient.scan(productParams, function (err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
data.Items.forEach(item => {
products.push(item)
});
}
});
var retailerParams = {
TableName: retailersTable,
FilterExpression: 'leadTime = :this_leadTime',
ExpressionAttributeValues: { ':this_leadTime': 42 }
};
dynamoClient.scan(retailerParams, function (err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
data.Items.forEach(item => {
retailers.push(item)
});
}
});
var email = {
"Source": "[email protected]",
"Template": "some_template",
"Destination": {
"ToAddresses": ["[email protected]"]
},
"TemplateData": `{somedata}`
}
await ses.sendTemplatedEmail(email).promise();
Upvotes: 0
Views: 1278
Reputation: 7675
You can convert both DynamoDB calls into promises (by chaining scan
calls with .promise()
calls) and await
them using Promise.all
before sending the email:
var productParams = {
TableName: productsTable,
FilterExpression: 'client = :this_client',
ExpressionAttributeValues: { ':this_client': "someclient" }
};
const productsPromise = dynamoClient.scan(productParams).promise()
.then(data => {
data.Items.forEach(item => {
products.push(item)
});
})
.catch(err => {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
});
var retailerParams = {
TableName: retailersTable,
FilterExpression: 'leadTime = :this_leadTime',
ExpressionAttributeValues: { ':this_leadTime': 42 }
};
const retailersPromise = dynamoClient.scan(retailerParams).promise()
.then(data => {
console.log("Query succeeded.");
data.Items.forEach(item => {
retailers.push(item)
});
})
.catch(err => {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
});
await Promise.all([
productsPromise,
retailersPromise
]);
var email = {
"Source": "[email protected]",
"Template": "some_template",
"Destination": {
"ToAddresses": ["[email protected]"]
},
"TemplateData": `{somedata}`
}
await ses.sendTemplatedEmail(email).promise();
Upvotes: 2