I have a call to AWS where I get a response and the callback looks like so:
const handleResponse = async (response) => {
var responseBody = "";
response.on("data", async function (chunk) {
responseBody += chunk;
});
response.on("end", async function (chunk) {
return responseBody;
});
return responseBody;
};
My current attempt is to call this function with an await like such:
const getLoadIds = async (payload) => {
// console.log(payload);
const resp = await handleResponse(payload)
console.log(resp) <--- this is undefined
}
How can I get the response from the response.on("end") call?
Here is the original caller code:
var client = new AWS.HttpClient();
try {
await client.handleRequest(request, null, async (res) => fn(res));
} catch (err) {
fn is an alias to getLoadIds
You might want to have something like
const handleResponse = (response) => {
return new Promise((resolve) => {
var responseBody = "";
response.on("data", function (chunk) {
responseBody += chunk;
});
response.on("end", function (chunk) {
resolve(responseBody);
});
});
};
upd: thanx @Andrew Li, noticed bug issue in the answer
Wrap the stream handler in a promise. resolve it if returns data, and reject if it has an error.
function handleResponse() {
let responseBody = '';
return new Promise((res, rej) => {
response.on('data', (chunk) => responseBody += chunk);
response.on('end', () => res(responseBody));
response.on('error', (error) => rej(error));
});
};
function getLoadIds(payload) {
const resp = await handleResponse(payload);
console.log(resp);
}