【问题标题】:Problem sending post request from amazon-lambda从 amazon-lambda 发送帖子请求时出现问题
【发布时间】:2019-11-15 14:41:33
【问题描述】:

在将消息从亚马逊队列 (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,但我不知道我必须在哪里做请求。

【问题讨论】:

    标签: javascript node.js aws-lambda amazon-sqs


    【解决方案1】:

    我认为真正的问题是因为您的请求功能立即解决成功而没有侦听错误,这是无用的。名为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();
    
       });
    }
    

    【讨论】:

      【解决方案2】:

      你可能是对的!

      尝试将promise.all 放在forEach 之外。

      您可以使用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;
                  }
      
      
          };    
      

      【讨论】:

      • 谢谢!它有效,但我认为我没有得到诀窍,那么 .then 和 await 之间有什么区别?
      • 基本上唯一的区别是一个更等同于同步语言的sintax......你可以在这里阅读更多:blog.pusher.com/promises-async-await
      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2023-01-13
      相关资源
      最近更新 更多