0

So, i tried multiple solutions here to wait for api response inside for loop, but each time my loop isn't waiting for that api and is rendering page without data. Here is some code

let data = [];
    const promises = [];
    let count = 0;
    const files = req.files;

    files.forEach(function (file) {
      optSettings.file = file.path;
      const promise = cheetaho.optimizeUpload(optSettings, (err, response) => {
        if (err) {
          console.log(err);
          reject(err);
        } else {
          data.push(response);
          fs.unlink(file.path, (err) => {
            if (err) {
              console.log(err);
            }
          });
          count++;
          resolve();
        }
      });
      console.log(promise);
      promises.push(promise);
    });

    Promise.all(promises).then(() => {
      console.log(data);

      res.render("index", {
        rendered: true,
        imageData: data,
        name: files[0].originalname,
      });
    });

Question is how can i wait for that response, push that response to data array and after all render index?

Thank you in advance.

  • The return value of `cheetaho.optimizeUpload` doesn't appear to be a promise (the two big blues are that your attempt to treat it as one isn't working, and the function takes a callback function). – Quentin Mar 11 '23 at 11:05
  • ForEach doesn't understand async calls, try to use for instead – Antek Pietryga Mar 11 '23 at 11:14

0 Answers0