0

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

3
  • 2
    handleResponse is not doing anything asynchronously... It just immediately returns the empty string. Commented Sep 22, 2021 at 16:48
  • 2
    That is because you are returning right away from handleResponse. To do this, remove async from the function, then return a promise instead from handleResponse that resolves to responseBody when the end event occurs. Remove async from your callbacks. Commented Sep 22, 2021 at 16:48
  • @AndrewLi Do you mind posting an example of this flow? Commented Sep 22, 2021 at 16:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget error handling though
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.