1

I need to execute a promise within a loop and then resolve the result to another promise. But the issue is that the Promises.all() function doesnt seem to accept the promise the code is as follows:

return new Promise((resolve, reject) => {
    let Path = []
    let referencesLoop = []
    for (let i = 0; i < Response.length; i++) {
      referencesLoop.push(new Promise((resolve, reject) => {
        if (assetClass && searchTerm) {
          const fileName = `${process.env.FILE_OUTPUTPATH}/${assetClass}/${searchTerm.split(' ').join('_')}/${Response[i]}`
          const fileNewName = `${process.env.FILE_OUTPUTPATH}/${assetClass}/${searchTerm.split(' ').join('_')}/${searchTerm.split(' ').join('_')}_${Response[i]}`
          const bucketFileName = `${BUCKET_NAME}/${searchTerm.split(' ').join('_')}_${Response[i]}`
          if (fs.existsSync(fileName)) {
            console.log(Response[i], searchTerm)
            fs.rename(fileName, fileNewName,
              async function (error, data) {
                if (error) {
                  reject(error)
                } else {
                  try {
                    const res = await gcs.bucket(BUCKET_NAME).upload(fileNewName, {
                      // gzip: true,
                      metadata: {
                        // Enable long-lived HTTP caching headers
                        // Use only if the contents of the file will never change
                        // (If the contents will change, use cacheControl: 'no-cache')
                        cacheControl: 'public, max-age=31536000',
                      }
                    });
                    const gclouduri = `https://storage.googleapis.com/${bucketFileName}`;
                    console.log(searchTerm, 'gcloud uri')
                    console.log(gclouduri)
                    Path.push(gclouduri);
                  } catch (error) {
                    console.error(error)
                    console.log('error at bucket upload')
                    Path.push(undefined);
                  }
                }
                console.log('^^^^^^^^^^^^^^^^^^^^^^')
                console.log(Path)
                resolve(Path) //I get the Expected output here
              });
          }
        }
      }));
    }
    console.log(referencesLoop)
    Promise.all(referencesLoop).then((ref) => {
      console.log('in reference')
      resolve(ref)
    });
  })

I tried to see what was being passed into Promise.all and thus logged the referenceLoop and it printed

Promise {
    _bitField: 0,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: undefined,
    _promise0: undefined,
    _receiver0: undefined }

The promise handling somewhere seems to be wrong but i am not able to single out where or what exactly is missing.

anubysh
  • 576
  • 6
  • 18
  • You're only conditionally calling `resolve` (or `reject`) - `if (assetClass && searchTerm) {` if that does not evaluate to `true`, the `Promise.all` will remain unresolved (and unthrown) forever – CertainPerformance Jan 04 '19 at 08:45
  • Don't use callback-based `fs` together with promises. There's https://nodejs.org/api/fs.html#fs_fs_promises_api . Don't use `new Promise` when there's already a promise, this is promise construction antipattern. – Estus Flask Jan 04 '19 at 08:45
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 04 '19 at 09:01

0 Answers0