【发布时间】:2020-02-25 05:02:57
【问题描述】:
我正在尝试使用 Nodejs 编写 AWS Lambda 函数。
在代码中,我必须调用 API,等待响应并使用该数据执行其他操作(我还没有写任何关于此的内容) 注意:很抱歉将 customerTAX 声明为全局变量,但我更喜欢使用 lambda 函数,然后尝试从函数 isself 返回值。
这是代码:
'use strict';
var customerTAX;
const https = require('https');
const options = {
host: 'xxxxxxx.com',
port: 443,
path: '/yyyyyyy.json',
method: 'POST',
headers: {
'Content-Type': 'application/graphql',
}
};
exports.handler = async (event) => {
const body = JSON.parse(event.body);
const orderId = body.id;
const customerId = body.customer.id;
console.log('ORDER ID: ' + orderId);
console.log('CUST ID: ' + customerId);
const query = `xxxxxxxxxxxxxxxxxxxx`;
//I CAN SEE ALL LOGS OF THIS FUNCTION IN CLOUDWATCH
await getCustomerTAX(query);
//I CAN'T SEE NOTHING BELOW THIS LINE IN AWS CLOUDWATCH
console.log('CUST TAX: ' + customerTAX);
if (customerTAX != null) {
console.log('LETs GO TO SAVE IT')
} else {
console.log('NOTAX: No customerTAX');
}
const response = {
statusCode: 200,
body: JSON.stringify(event.body),
};
return response;
};
var getCustomerTAX = function(query) {
return new Promise(function(resolve, reject) {
var req = https.request(options, function(res) {
res.setEncoding('utf8');
var bodyRaw = '';
res.on('readable', function () {
var chunk = this.read() || '';
bodyRaw += chunk;
console.log('getTAX CHUNK (' + Buffer.byteLength(chunk) + ' bytes): ' + chunk);
});
res.on('end', function () {
const body = JSON.parse(bodyRaw);
if (body.TAX.value != null) {
customerTAX = body.TAX.value;
} else {
customerTAX = null;
}
console.log("getTAX END: " + customerTAX);
resolve;
//console.log('body: ' + Buffer.byteLength(body) + ' bytes');
});
});
//handle the possible errors
req.on('error', function(e) {
console.log("ERROR: " + e);
reject(e);
});
//do the request
req.write(query);
//finish the request
req.end();
});
};
函数 getCustomerTAX 完美运行,但我不知道为什么我的 lambda 函数在这一行中“完成”了,而且我在 cloudwatch 中看不到更多控制台日志。
希望您的回答,非常感谢。
【问题讨论】:
-
您的退货声明后有一个额外的
},这是错字吗? -
是的,额外的
}是一种类型,抱歉。我刚刚编辑了它
标签: node.js amazon-web-services asynchronous async-await aws-lambda