Extract result of a function

1

Good people, I have this function that I use to analyze some texts, the issue is that I need to include the data in an array, I do this within the function using data, which brings this function, but then the variable 'sentiments' is empty, and I can not use it outside the function, what would be the way to get sentiments, the push is made and arrive with the results to the callback?

        for(var i=0; i<texts.length; i++){
          ibmWatson.analize(texts[i], function (error, data)
           {
              sentiments.push(data.result);
           });
        }

         callback(null, sentiments);
    
asked by Santiago D'Antuoni 09.01.2018 в 16:00
source

1 answer

1

You need to make sure that the function has been executed as many times as necessary. Actually your loop does not execute it, simply declares its execution N times where N is texts.length :

let analyzedCount = 0; //numero de ejecuciones de la función addToSentiments

for(var i = 0; i < texts.length; i++){
  ibmWatson.analize(texts[i], function addToSentiments (error, data) {
    sentiments.push(data.result);
    analyzedCount++;
    if (analyzedCount === texts.length) {
      callback(null, sentiments); //si se ha ejecutado todas las veces, llamamos
    } 
  });
}

Simplified execution example:

let datos=[1,2,3,4,5,6];
let sentiments=[];

let analyzedCount = 0;

function analizar(dato,funcionCallback) {
    setTimeout(() => {
      console.log('Analizando ${dato}');
      funcionCallback(null,dato*10);
    });
}

function callback(algo) {
  console.log(algo);
}    
for(var i = 0; i < datos.length; i++){
  analizar(datos[i], function (error, data) {
    sentiments.push(data);
  analyzedCount++;
    if (analyzedCount === datos.length) {
      callback(sentiments); //si se ha ejecutado todas las veces, llamamos
    } 
  });
}

console.log('bucle terminado');
    
answered by 09.01.2018 / 16:09
source