Read jade array value

Asked

Viewed 34 times

0

I have the following array created in my controller:

var data = [];
for (var i = 0; i < array.length; i++) {
    nfejs(array[i], function(err, nfe) {
        var itemNfe = {};
        itemNfe.name = nfe.identificador.getNumero();
        data.push(itemNfe);
    });
}

nfe.data = data;

Which is generated as follows:

data:[{
    name: {type: String, required: true, trim: true, default: ""},
}],

I’m trying to read in jade as below, but it doesn’t work:

table#nfe.table.table-striped.table-bordered.table-hover.dt-responsive  
          thead  
            tr  
              th(style='text-align: center') Nome  
                th(style='text-align: center; width: 25%') Ação  
          tbody  
            for nfe in nfes  
              tr  
                td(style='text-align: center') #{nfe[data].name}  

1 answer

0

You have an asynchronous problem. Your cycle for is running asynchronous functions, and the cycle ends before functions have been run.

That is to say the order of events is:

> começa o ciclo for 
  > inicia as funçöes assíncronas 
    > acaba o ciclo for 
      > corre "nfe.data = data;" 
        > as respostas das funções chamadas dentro do for começam a chegar

To solve this you have to wait for the asynchronous functions to have run. I usually use the library async to do this. In this case the code could be like this:

var async = require('async');
async.map(array, function(el, cb) {
    nfejs(el, function(err, nfe) {
        var itemNfe = {};
        itemNfe.name = nfe.identificador.getNumero();
        cb(err, itemNfe); // quando "nfejs" tiver dado a resposta, chama a callback "cb"
    });
}, function(err, res) { // esta é a callback final, ou seja quando tiver chamado e recebido todas as "nfejs"
    nfe.data = res;
    // aqui os dados estão disponíveis e só agora (dentro desta callback)
    // é que podes correr ou chamar código que precise de "nfe.data"
});

And then at Jade you can wear it like this:

tbody  
  each nfe in nfes.data
    tr  
      td(style='text-align: center') #{nfe.name}  
  • I’m not in trouble to assemble the array, the same is correct. My difficulty is in how to read in jade.

  • @Nodejs ok, if the function nfejs It’s synchronous, so all you need to do is correct Jade. I added that to the answer.

  • @Nodejs one possible question: are you passing the nfes for the right Jade? in this case I put in the answer each nfe in nfes.data, but if you’ve only passed nfes.data for Jade, you can have only each nfe in nfes or the variable you use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.