我正在尝试创建一个异步lambda函数,该函数会进行http Get调用,以使其无法正常工作,并且我认为它与异步有关。如果删除await / async并使它同步,则我的函数可以正常工作。我不确定自己在做什么错。谢谢您的帮助!
exports.handler = async function (event, context) {
await setBattery();
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
async function setBattery() {
'use strict';
const https = require('https');
const options = {
hostname: 'testsite.com',
port: 443,
path: '/proxy/api/setting?EM_OperatingMode=1',
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.end();
}
根据MDN Web文档:
异步函数声明定义了一个异步函数,其中返回一个AsyncFunction对象。异步函数是通过事件循环异步运行的函数,使用隐式承诺要返回其结果。但是语法和结构您使用异步功能的代码更像使用标准同步功能。
因此,您需要返回一个Promise
对象,以便由您的async function
处理(您也可以使用另一个诺言来处理它),我将setBattery
转换为普通函数,然后将该函数返回现在是一个由您的处理程序(exports.handler
)处理的承诺。我还没有测试代码,但是应该可以。
exports.handler = async function (event, context) {
await setBattery();
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
function setBattery() {
'use strict';
const https = require('https');
const options = {
hostname: 'testsite.com',
port: 443,
path: '/proxy/api/setting?EM_OperatingMode=1',
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
};
// Return it as a Promise
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
// If successful
resolve(d);
});
});
req.on('error', error => {
console.error(error);
// If failed
reject(error);
});
req.end();
});
}