【问题标题】:AWS SQS Node.js script does not awaitAWS SQS Node.js 脚本不等待
【发布时间】:2019-05-02 09:03:18
【问题描述】:

尝试发送多条消息(来自 AWS SQS lambda,如果这很重要),但它从不等待承诺。

function getEndpoint(settings){
    return new Promise(function(resolve, reject) { 
    // [...] more stuff here
}

然后循环调用:

exports.handler = async (event) => {
    var messages = [];
    event.Records.forEach(function(messageId, body) {
        //options object created from some stuff
        messages.push(getEndpoint(options).then(function(response){
            console.log("anything at all"); //NEVER LOGGED
        }));
    });
    await Promise.all(messages);
};

但是 await 似乎完全被跳过了。我不确定我是如何通过明确的await 获得Process exited before completing request 的。我在其他有效的脚本中有类似的异步等待/承诺设置,但无法发现我在这个脚本中做错了什么。

【问题讨论】:

  • 介意分享更多代码吗?这段摘录看起来不错。
  • @enapupe 添加了远程调用功能,但这真的只是整个事情
  • 希望看到主要调用的 fn 主体.. 您仅分享了其中的一部分。 getEndpoint 部分似乎没问题
  • @enapupe 除了实际的 https 呼叫设置(出于安全原因,我无法分享),一切都在这里。但如果这是问题所在,我会收到错误,不是吗?

标签: node.js async-await aws-lambda amazon-sqs


【解决方案1】:

你忘了给 lambda 返回一些东西:

exports.handler = async (event) => {
    var messages = [];
    event.Records.forEach(function(messageId, body) {
        //options object created from some stuff
        messages.push(getEndpoint(options));
    });
    await Promise.all(messages);
    return 'OK'
};

这也应该有效:

exports.handler = (event) => { // async is not mandatory here
    var messages = [];
    event.Records.forEach(function(messageId, body) {
        //options object created from some stuff
        messages.push(getEndpoint(options));
    });
    return Promise.all(messages); // returning a promise
};

你可以使用地图:

exports.handler = (event) => { // async is not mandatory here
    const messages = event.Records.map(function(messageId, body) {
        //options object created from some stuff
        return getEndpoint(options)
    });
    return Promise.all(messages); // returning a promise
};

要了解为什么会发生这种情况,您必须深入了解 lambda 的实现:它本质上会等待函数堆栈被清除,并且由于您根本没有返回任何内容,因此函数堆栈在排队后立即为空所有的东西 - 在 await 调用之后添加一个简单的 return 会使 fn 堆栈不为空,这意味着 lambda 将等待它完成。

如果你在标准节点上运行它,你的函数也会在承诺完成之前返回,但你的节点进程在堆栈被清除之前不会退出。这是 lambda 与股票节点不同的地方。

【讨论】:

  • 太棒了。感谢您提供所有详细信息,很高兴了解正在发生的事情。
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 2019-11-12
  • 2021-03-08
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
相关资源
最近更新 更多