Read array value in jade

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;

That is generated as follows:

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

I'm trying to read in jade as below, but it does not 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}  
    
asked by anonymous 27.04.2016 / 23:51

1 answer

0

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

In other words, the event order 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 run. I usually use the library async to do this. In this case the code could look 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 in Jade you can use it like this:

tbody  
  each nfe in nfes.data
    tr  
      td(style='text-align: center') #{nfe.name}  
    
28.04.2016 / 00:01