0

For some reason the then function is being executed before the part inside promise.all() is executed

const Uploader = async (req, res, myFunc) => {
const fileIds = req.body.fileIds;
const dataArray = [];

await Promise.all([
  fileIds.forEach(fileId => {
    fileServer.UploadCreds(req.user.organization.ssoId, req.user.ssoId, (err, data) => {

      console.log(" in promise 1----",dataArray)
      data.fileId = fileId,
      dataArray.push(data)
      console.log(" in promise 2----",dataArray)

    });           
  })
]).then(()=>{
  console.log(" in promise 3----",dataArray)
  return myFunc(req.params.id, req.user, dataArray, apiUtils.respond(res))
})
};

I have also attempted replacing await with return, calling myFunc from inside promise all and returning that but "in promise 3" always prints with an empty array before the other two logs. I have also tried adding a catch block incase promise was failing but it wasn't.

mocha
  • 45
  • 6
  • Is it executed before Promise.All or before Promise.All finished? Is UploadCreds an async function? – 3r1c Jun 07 '21 at 05:51
  • Your question was closed with a link to how to "promisify" a call with a callback, but that's not the only thing that's going wrong. The other problem is that the return value is not being passed to Promise.all. Once you are initializing the Promises properly, you have to run fileIds.map(id => { ... return thePromise }), not fileIds.forEach(id => { ... return thePromise }). – Mattias Martens Jun 07 '21 at 05:52
  • `forEach()` always returns `undefined`. You're basically waiting for `Promise.all([ undefined ])` to finish. – Thomas Jun 07 '21 at 05:59
  • @MattiasMartens I tried what you suggested with the map (returning data to dataArray) but returned something like [ [ undefined, undefined ] ], any idea what else i might be doing wrong? – mocha Jun 07 '21 at 06:18
  • @Mocha Did you check what's at the link "How do I convert an existing callback API to promises?" The library function appears to take a callback, a version of async that was popular before Promises were added to the language. To get a Promise from it, you can try something like this: return new Promise((resolve, reject) => { fileServer.UploadCreds(req.user.organization.ssoId, req.user.ssoId, (err, data) => { if (err) { reject(err) } else { data.fileId = fileId; dataArray.push(data); resolve(); } }) – Mattias Martens Jun 07 '21 at 16:48

0 Answers0