我目前正在学习如何将我的Amazon Lambda函数(在js中)连接到API。我发现以下代码可以正常工作,但是我一般对JavaScript和API还是陌生的,并且不确定它在做什么。有人可以向我解释此功能的作用以及如何工作吗?谢谢!
函数httpGet(){返回新的Promise((((resolve,reject)=> {
var options = {
host: 'api.icndb.com',
port: 443,
path: '/jokes/random',
method: 'GET',
};
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
response.on('data', (chunk) => {
returnData += chunk;
});
response.on('end', () => {
resolve(JSON.parse(returnData));
});
response.on('error', (error) => {
reject(error);
});
});
request.end();
}));}
这里response
对象是一个node.js stream,特别是一个“推送”流。 (This文章很好地解释了推/拉流)。
const request = https.request(options, (response) => {
// Here response is a stream, which will emit
// a 'data' event when some data is available.
response.setEncoding('utf8');
let returnData = '';
// A chunk of data has been pushed by the stream,
// append it to the final response
response.on('data', (chunk) => {
returnData += chunk;
});
// All the data has been pushed by the stream.
// 'returnData' has all the response data. Resolve the
// promise with the data.
response.on('end', () => {
resolve(JSON.parse(returnData));
});
// Stream has thrown an error.
// Reject the promise
response.on('error', (error) => {
reject(error);
});
});
request.end();