Reputation: 3
I am trying to send http requests in POST from a amazon-lambda function after retrieving the messages from the amazon queue (sqs) to my API. The API integrate this messages in my database. for that I use Node.js with the system of promises but when I send a lot of messages in the queue the requests are not send and I do not understand why.
I tried several methods including with promiseAll but without success
const http = require('http');
var promises = [];
const options = {
host: process.env.Host,
path: process.env.Path,
port: process.env.Port,
method: process.env.Method
};
exports.handler = async (event, context) => {
event.Records.forEach(record => {
const {
body
} = record; // the messages from the bus
promises.push(PromiseCreator(body));
Promise.all(promises)
.then(function(data) {})
.catch(function(err) {
return err
});
});
};
function PromiseCreator(body) {
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
resolve('succès');
});
req.on('error', (e) => {
reject(Error(e));
});
// send the request
req.write(body);
req.end();
});
}
I think the problem comes from the forEach, but i don't where i have to do the request.
Upvotes: 0
Views: 117
Reputation: 155
I think the real problem is because your request function is resolving success immediately without listening for errors, which is useless. Your function named PromiseCreator
should have a structure like the following example:
function PromiseCreator(body) {
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
if (res.statusCode !== 200) {
reject("Connection error");
}
res.on('error', (error) => {
reject(error);
});
});
req.on('error', (e) => {
reject(Error(e));
});
req.on("finish", () => {
resolve("success");
})
// send the request
req.write(body);
req.end();
});
}
Upvotes: 1
Reputation: 548
You probably right!
Try put the promise.all
outside of forEach
.
And you can use await
instead .then
exports.handler = async (event, context) => {
event.Records.forEach(record => {
const { body } = record; // the messages from the bus
promises.push(PromiseCreator(body));
});
try {
await Promise.all(promises);
} catch(err) {
return err;
}
};
Upvotes: 0