问题:我几乎没有使用异步等待函数的经验,我试图在if-else语句中执行嵌套的异步等待函数,该语句依赖于更高级别的异步函数在事件检测时执行.我希望从嵌套的异步函数返回一个成功的http响应,但我继续为响应获取空值.然而,嵌套的异步函数在if-else语句之外按预期工作.我的目标是简单地让代码中的"等待新promise "部分在条件if-else语句中返回http响应.感谢您的帮助.
我try 过的内容:除了搜索具有类似问题的问题之外,我还没有真正try 过纠正这种情况,因为我对异步等待函数的性质知之甚少.
代码:
exports.handler = async (event) => {
const sensorId = event.sensorId;
ddb.scan(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
console.log(typeof(data));
data.Items.forEach(function (item, index, array) {
console.log("printing", item);
console.log('Testing', item.sensorId.S);
if (item.sensorId.S == sensorId) {
console.log('New sensorId was not created. Already Exists.');
return ;
}
else {
// Here is the nested async await function
async () => {
console.log(event.sensorId);
const req = new AWS.HttpRequest(appsyncUrl, region);
const item = {
input: {
id: event.sensorId,
sensorId: event.sensorId
}
};
req.method = "POST";
req.path = "/graphql";
req.headers.host = endpoint;
req.headers["Content-Type"] = "application/json";
req.body = JSON.stringify({
query: print(createSensor),
operationName: "createSensor",
variables: item
});
console.log(typeof(graphqlQuery));
if (apiKey) {
req.headers["x-api-key"] = apiKey;
} else {
const signer = new AWS.Signers.V4(req, "appsync", true);
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());
}
const data = await new Promise((resolve, reject) => {
const httpRequest = https.request({ ...req, host: endpoint }, (result) => {
let data = "";
result.on("data", (chunk) => {
data += chunk;
});
result.on("end", () => {
resolve(JSON.parse(data.toString()));
});
});
httpRequest.write(req.body);
httpRequest.end();
});
try {
return {
status代码: 200,
body: data
};
}
catch(err) {
console.log('error', err);
}
};
}});
}
});
预期结果:
Response
{
"statusCode": 200,
"body": {
"data": {
"createSensor": {
"id": "fd78597a-12fd-4bd1-9f9d-6ee1a88e197d",
"digit": null,
"date": null,
"timestamp": null
}
}
}
}
实际结果:
Response
null