Reputation: 11882
I looking for a exemple of AWS SQS send message in a loop by AWS Lambda NodeJs 18 (so aws-sdk V3).
exports.handler = async function (event) {
const mydatas = JSON.parse(event.body);
/* ..... */
const sqsClient = new SQSClient({ apiVersion: '2012-11-05' });
await mydatas.forEach(async mydata => {
const command = new SendMessageCommand({
DelaySeconds: 10,
MessageAttributes: {
'x': {
DataType: 'Number',
StringValue: `${mydata.a}`
},
'y': {
DataType: 'Number',
StringValue: `${mydata.b}`
},
'z': {
DataType: 'Number',
StringValue: `${mydata.c}`
}
},
MessageBody: 'My_message',
QueueUrl: process.env.MY_SQS_URL
});
await sqsClient.send(command)
.then((data) => console.log(data))
.catch((err) => console.log(err));
});
return {
statusCode: 200,
body: "OK",
};
};
My problem is await sqsClient.send(command)
never execute.
I see await inside a for loop in a lambda in node.js And I think use Promise.all
but send
is not a function.
await Promise.all(mybaseUrl.map((base) => {
/* rest of the code... */
return sqsClient.send(command).promise();
}));
EDIT
is it a sample without loop: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sqs_code_examples.html
Upvotes: 1
Views: 546
Reputation: 8885
The answer Stéphane GRILLON is correct. To clarify, your problem is that you are using .forEach
, which doesn't support the async/await syntax. Instead, you can use .map
and await Promise.all
on the results of the map.
exports.handler = async function (event) {
const mydatas = JSON.parse(event.body);
/* ..... */
const sqsClient = new SQSClient({ apiVersion: '2012-11-05' });
await Promise.all(mydatas.map(async mydata => {
const command = new SendMessageCommand({
DelaySeconds: 10,
MessageAttributes: {
'x': {
DataType: 'Number',
StringValue: `${mydata.a}`
},
'y': {
DataType: 'Number',
StringValue: `${mydata.b}`
},
'z': {
DataType: 'Number',
StringValue: `${mydata.c}`
}
},
MessageBody: 'My_message',
QueueUrl: process.env.MY_SQS_URL
});
await sqsClient.send(command)
.then((data) => console.log(data))
.catch((err) => console.log(err));
}));
return {
statusCode: 200,
body: "OK",
};
};
Upvotes: 0
Reputation: 11882
I use juste Promise.all...
and no .promise()
after sqsClient.send(command)
/* eslint-disable no-undef */
'use strict';
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs');
exports.handler = async function (event) {
const mydatas = JSON.parse(event.body);
const sqsClient = new SQSClient({ apiVersion: '2012-11-05' });
await Promise.all(mydatas.map(async (mydata) => {
const command = new SendMessageCommand({
DelaySeconds: 10,
MessageAttributes: {
'x': {
DataType: 'Number',
StringValue: `${mydata.a}`
},
'y': {
DataType: 'Number',
StringValue: `${mydata.b}`
},
'z': {
DataType: 'Number',
StringValue: `${mydata.c}`
}
},
MessageBody: 'My_message',
QueueUrl: process.env.MY_SQS_URL
});
const contents = await sqsClient.send(command);
console.log(contents);
}));
return {
statusCode: 200,
body: "OK",
};
};
Upvotes: 0