Ran*_*all 0 amazon-sqs node.js async-await aws-lambda
Trying to send several messages (from AWS SQS lambda, if that matters) but it's never waiting for the promises.
function getEndpoint(settings){
return new Promise(function(resolve, reject) {
// [...] more stuff here
}
Run Code Online (Sandbox Code Playgroud)
Which is then called in a loop:
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);
};
Run Code Online (Sandbox Code Playgroud)
But the await seems to be flat out skipped. I'm not sure how I'm getting Process exited before completing request
with an explicit await
. I have similar async await/promise setups in other scripts that work, but cannot spot what I've done wrong with this one.
你忘了向 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'
};
Run Code Online (Sandbox Code Playgroud)
这也应该有效:
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
};
Run Code Online (Sandbox Code Playgroud)
你可以使用地图:
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
};
Run Code Online (Sandbox Code Playgroud)
要理解为什么会发生这种情况,您必须深入了解 lambda 的实现:它本质上将等待函数堆栈被清除,并且由于您根本没有在其中返回任何内容,因此函数堆栈在将所有内容排队后立即变空- 在await
调用后添加一个简单的 return使 fn 堆栈不为空,这意味着 lambda 将等待它完成。
如果您在标准节点上运行它,您的函数也会在承诺完成之前返回,但您的节点进程在堆栈被清除之前不会退出。这是 lambda 与股票节点不同的地方。
归档时间: |
|
查看次数: |
369 次 |
最近记录: |