Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Unable to wait for async call in Javascript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!