Search code examples
node.jsexpressamazon-s3async-awaites6-promise

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

Solution

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