![](/img/trans.png)
[英]How to fix “await is only valid in async function” even when await is in an async function in Node.js?
[英]How to: await / async in a node.js lambda function?
我正在尝试创建一个异步 lambda function 使http Get call put it's not working normal 我相信它与异步有关。 如果我删除await/async并使其同步,我的 function 工作正常。 我不确定我做错了什么。 谢谢您的帮助!
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 文档:
async function 声明定义了一个异步 function,它返回一个 AsyncFunction object。 异步 function 是 function 通过事件循环异步操作,使用隐式 Promise 返回其结果。 但是使用异步函数的代码的语法和结构更像是使用标准同步函数。
So, You need to return a Promise
object in order to be handled by your async function
(You could also use another promise to handle it), I converted setBattery
to a normal function and the return of this function is now a promise that will be由您的处理程序( 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();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.