Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
NodeJS: How to fill Array through callback function

I hope the following code snippet is enough to explain my problem:

function getChildrensRoomsProductNumbers(uuids, callback) {
        var productNumbers = [];
        uuids.forEach(uuid => getProductNumber(uuid, function(productNumber){
            productNumbers.push(productNumber);}))
        callback(productNumbers);
    }

So for an array of uuids, I'd like to request the corresponding product numbers from an online shop and store them in the array productNumbers which then I'd like to pass to a parent function for further manipulation through calling callback(productNumbers)

The request itself is done in the getProductNumber function.

However, I don't understand why the array productNumbers is empty? I know forEach is not returning anything so that's why I prepared an array beforehand that should be filled in my idea.

I'm relatively new to NodeJS/JavaScript, so I probably might be missing some basic concepts here.

This is the getProductNumber function:

function getProductNumber(uuid, callback){
    getToken(function(err, token){
        var headers = {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json',
        };
        const options = {
            url: BASE_URL + 'api/product/' + uuid,
            method: 'GET',
            headers: headers
        };

        axios.request(options)
            .then(res => {
                console.log("NUmber: " + res.data.data.productNumber);
                callback(res.data.data.productNumber);
            })
            .catch(err => {
                console.error(err.response);
            });
        })
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

please first learn async/await style to get rid of callbacks

then this will be doable :

    async function getChildrensRoomsProductNumbers(uuids) {
        var productNumbers = [];
        for (let uuid of uuids) {
            const productNumber = await getProductNumber(uuid);
            productNumbers.push(productNumber);
        }
        return productNumbers;
    }

like people said in comments getProductNumber looks like it does an async job. if you wat to stick with callbacks you can use https://www.npmjs.com/package/async to fire a callback when your loop is done.

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks to @Raphael PICCOLO for pointing out the util.promisify function.

On that basis, I promisified the function which I have to obtain the shop api token and have the rest to work with async/await, like so:

const awaitablegetToken = util.promisify(getToken);

async function getChildrensRoomsProductNumbers(uuids) {
    var productNumbers = [];
    var accessToken = await awaitablegetToken();
    for (const uuid of uuids){
        const productNumber = await getChildrensRoomsProductNumber(uuid, accessToken)
        productNumbers.push(productNumber);
    }
    return productNumbers;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda