Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await - data is undefined

Trying to convert CSV to JSON, then download an image,then upload it to S3 bucket, then update current JSON and finally generate a new CSV. However the code doesn't wait for the async function to complete so const data = await handle_image_URLs(csv); returns as undefined.

//parse CSV - extract images, then upload to S3 bucket
const handle_image_URLs = file => {
  new Promise((resolve, reject) => {
    fs.createReadStream(file)
      .pipe(csv_to_json())
      .on("data", async data => {
        // console.log("data", data);
        try {
          if (is_image_url(data.image_link)) {
            console.log("data.image_link", data.image_link);
            image_buffer = await download_image(data.image_link);
            name = uuid() + ".jpg";
            const location = await upload_to_S3(image_buffer, name);
            //Inject back updated image url
            data.image_link = location.Location;
            //New generated data goes into an array
            results.push(data);
          }
          // console.log("RESULT", results);
          resolve(results);
        } catch (error) {
          reject(error);
        }
      });
  });
};

express to handle a csv upload

app.post("/", upload.single("file"), async (req, res) => {
  const file = req.file;
  const csv = `./uploads/${file.originalname}`;
  const data = await handle_image_URLs(csv);
  console.log("DATA", data);
  // await json_to_csv_converter.json2csv(data, json2csvCallback);
  res.status(200).json({ message: "working " });
});
like image 746
Edgar Kiljak Avatar asked Mar 09 '26 16:03

Edgar Kiljak


1 Answers

Update the return new promise((resolve, reject)) to return new promise( async (resolve, reject)) and it should work

like image 100
Sagar Chilukuri Avatar answered Mar 11 '26 07:03

Sagar Chilukuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!