在将消息从亚马逊队列 (sqs) 检索到我的 API 后,我尝试从 amazon-lambda 函数以 POST 方式发送 http 请求。 API 将此消息集成到我的数据库中。 为此,我将 Node.js 与 Promise 系统一起使用,但是当我在队列中发送大量消息时,请求不会发送,我不明白为什么。
我尝试了多种方法,包括使用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();
});
}
我认为问题来自于 forEach,但我不知道我必须在哪里执行请求。
最佳答案
我认为真正的问题是因为你的请求函数立即解决成功而不监听错误,这是无用的。名为 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();
});
}
关于javascript - 从 amazon-lambda 发送 post 请求时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894997/