Javascript promise的JS代码在AWS lambda上不起作用,但在更改为异步/等待样式时起作用
我试图在AWS Lambda上创建一个函数,使用Twilio API向手机发送短信。我使用的是Node.JS,主要遵循本文中的说明: 我从那篇文章中得到的发送短信的代码是:Javascript promise的JS代码在AWS lambda上不起作用,但在更改为异步/等待样式时起作用,javascript,node.js,aws-lambda,serverless,Javascript,Node.js,Aws Lambda,Serverless,我试图在AWS Lambda上创建一个函数,使用Twilio API向手机发送短信。我使用的是Node.JS,主要遵循本文中的说明: 我从那篇文章中得到的发送短信的代码是: exports.handler = (event, context, callback) => { // Your Account SID from www.twilio.com/console // See http://twil.io/secure for important security i
exports.handler = (event, context, callback) => {
// Your Account SID from www.twilio.com/console
// See http://twil.io/secure for important security information
const accountSid = process.env.ACCOUNT_SID;
// Your Auth Token from www.twilio.com/console
// See http://twil.io/secure for important security information
const authToken = process.env.AUTH_TOKEN;
// Import Twilio's Node Helper library
// Create an authenticated Twilio Client instance
const client = require('twilio')(accountSid, authToken);
// Send a text message
client.messages.create({
body: 'Hello from Lambda!',
to: '+12345678901', // your phone number
from: '+12345678901' // a valid Twilio number
})
.then((message) => {
// Success, return message SID
callback(null, message.sid);
})
.catch((e) => {
// Error, return error object
callback(Error(e));
});
};
当我在AWS上创建lambda时,我选择了Hello World模板,它将exports.handler回调标记为async
,就像这样exports.handler=async(事件、上下文、回调)=>{
。我没有注意到这个async关键字,从那篇文章中复制粘贴了方法体,最终将async/wait
代码与promise风格的混合在一起。然后
代码。我首先从我的计算机本地测试了这段代码,它起作用了,因为我只是使用了方法体,没有任何顶级函数或任何东西。但是当我运行来自AWS Lambda,正确记录了环境变量,但在此之后,我没有收到任何其他O/P或错误。在浪费了大量时间后,我决定将链式承诺样式代码更改为异步/等待样式代码,并成功运行。我修改的代码如下:
exports.handler = async (event, context, callback) => {
// Your Account SID from www.twilio.com/console
// See http://twil.io/secure for important security information
const accountSid = process.env.ACCOUNT_SID;
// Your Auth Token from www.twilio.com/console
// See http://twil.io/secure for important security information
const authToken = process.env.AUTH_TOKEN;
// Import Twilio's Node Helper library
// Create an authenticated Twilio Client instance
const client = require('twilio')(accountSid, authToken);
try {
const messageSid = await client.messages.create({
body: 'Hello from Lambda!',
to: '+12345678901', // your phone number
from: '+12345678901' // a valid Twilio number
});
}
catch(err) {
callback(Error(err));
}
};
我的问题是,将async/Wait与承诺类型代码(.then construct)混合使用是否错误?如果我在第一行代码中添加async关键字,它将不起作用。为什么会发生这种情况?您不应该将两者结合使用。详细信息可在此处找到: 一个关键是: 对于非异步处理程序,函数执行将继续,直到事件循环为空或函数超时。在所有事件循环任务完成之前,响应不会发送给调用方。如果函数超时,则返回错误。您可以通过设置context.callbackaitsfore将运行时配置为立即发送响应mptyEventLoop到false 当您不使用
async
时,它将等待事件循环完成。当您使用async
时,它不会这样做,因为它希望您一直使用async