[英]Problem sending post request from amazon-lambda
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. 从Amazon队列(sqs)检索到我的API的消息后,我试图在POST中从amazon-lambda函数发送http请求。 The API integrate this messages in my database. API将这些消息集成到我的数据库中。 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. 为此,我在Promise系统中使用Node.js,但是当我在队列中发送大量消息时,请求没有发送,我也不明白为什么。
I tried several methods including with promiseAll but without success 我尝试了几种方法,包括promiseAll,但没有成功
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. 我认为问题出在forEach,但我不在我必须执行的请求中。
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: 您的名为PromiseCreator
函数应具有类似于以下示例的结构:
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();
});
}
You probably right! 你可能是对的!
Try put the promise.all
outside of forEach
. 尝试将promise.all
放在forEach
之外。
And you can use await
instead .then
你可以用await
来代替.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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.