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.