Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
How to store response data into an array out of the current function in node js?

How do i store all result data into pImages array i am getting the result but in that case i think async function will work but i dont know how to apply it. please help, my code is

exports.addImage = (req, res, next) => {
    let imageArray = req.files.productImageArray;

    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send("No files were uploaded.");
    }
    
    // here all images will be stored in array format
        let pImages = [];

         for (let f in imageArray) {
            imagekit.upload(
                {
                    file: imageArray[f].data, //required
                    fileName: imageArray[f].name, //required
                    customMetadata: {
                        color: req.body.productLabels[f],
                        default: req.body.defaultProduct[f]
                    }
                },
                function(error, result) {
                    if (error) console.log(error);
                    else {
                        console.log(result)
                        pImages.push(result)
                    }
                }
            );
        }

    console.log("p", pImages); //output p []
   
};

Thanks in Advance

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could wrap imagekit.upload(...) in a promise and then await this promise.

Therefore your promise has to be resolved or rejected in the callback on imagekit.upload.

Be aware that your addImage method now has to be async to use the await keyword and therefor returns a promise itself.

exports.addImage = async (req, res, next) => {
    let imageArray = req.files.productImageArray;

    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send("No files were uploaded.");
    }
    
    // here all images will be stored in array format
        let pImages = [];

         for (let f in imageArray) {
            try{
                const pImage = await new Promise((resolve,reject)=>{
                    imagekit.upload(
                        {
                            file: imageArray[f].data, //required
                            fileName: imageArray[f].name, //required
                            customMetadata: {
                                color: req.body.productLabels[f],
                                default: req.body.defaultProduct[f]
                            }
                        },
                        function(error, result) {
                            if (error){
                                reject(error);
                            } else {
                                resolve(result)
                            }
                        }
                    );
                });
                pImages.push(pImage);
            } catch(e){
                console.error(e);
            }
        }

    console.log("p", pImages); //output p []
   
};

There are other things in your code i haven't addressed.

In the first line you are accessing req.files.productImageArray without checking if req.files is defined. This check is done afterwords. So you should move your first line after this check.

Is req.files.productImageArray an array like the name says? If so you shouldn't use a for in loop use a for of loop instead and in your sanity checks you should include Array.isArray(req.files.productImageArray).

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda