-1

I need to transform a forEach in promise. The code is legacy and I can't use async/await operators.

Promise.all(Object.entries(data).forEach(function (data) {
    let [data1, data2] = data
    let info;

    consultData.getResponse(data1).then(result => info = result).then(function () {
        return dataServices.find(info)
            .then(function (result) {
                // do things
            })
            .then(function (info) {
                // do final things
            })
    })
})).then((result) => {
        // do something when all things have intereted and finished
    })

But output that Promise.all can't be used. If I try with Promise.resolve, the last is printed before all things have finished their processing.

How I can transform the forEach in a promise for i can use .then() after all iteration?

ASYNC/AWAIT DON'T WORK IN THIS CODE

Develop_SP
  • 382
  • 5
  • 19

1 Answers1

0

As @Jonas Wilms indicated, you can use .map returning each promise and after that you can use Promise.all

const entries = Object.entries(data);
const arrayOfPromises = entries.map((item) => {
  return new Promise((resolve, reject) => {
    const [data1, data2] = item;

    consultData.getResponse(data1).then((result) => {
      return dataServices.find(info);
    }).then((infoServiceResult) => {
      return resolve(infoServiceResult);
    }).catch((err) => {
      return reject(err);
    });
  });
});

Promise.all(arrayOfPromises).then((data) => {
  // data is an array of each infoServiceResult
  console.log(data);
}).catch((err) => {
  console.error(err);
});
Jose Mato
  • 2,709
  • 1
  • 17
  • 18
  • Please don't encourage the [Promise constructor antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). And @Develop_SP aside from the antipattern, this is almost exactly what I told you to do [in your last post](https://stackoverflow.com/questions/56045190/transform-foreach-in-promise-without-asyc-await?noredirect=1#comment98732311_56045190). In the future, please use [meta] if you believe your question was closed in error. Do not side-step moderation by asking exact duplicate questions. – Patrick Roberts May 08 '19 at 19:26