尝试发送几条消息(来自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);
};
但等待似乎很容易被忽略。我不知道我是如何得到Process exited before completing request
明确的await
。我在其他工作的脚本中有类似的异步等待/承诺设置,但是无法发现我对这个做错了什么。
你忘了把东西归还给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
};
你可以用map:
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
调用之后添加一个简单的返回使得fn堆栈不为空,这意味着lambda将等待它完成。
如果你在标准节点上运行它,你的函数也会在promises完成之前返回但是你的节点进程在堆栈被清除之前不会退出。这是lambda与stock节点不同的地方。