0

I have these two functions: one which analyses some data, and the other feeds it some data. Here the one which analyses the data translates the given text and runs it through an NLU model on IBM's Watson. For now I just want to store all the analysis results into 1 single Array and log it in the console.
My code:

const analyzeTweet = function(tweet){
    return new Promise((resolve,rejects)=>{
        translator(tweet).then(translation => {
            const options = {
                text: translation.text,
                features: {
                    entities: {model:auth.model},
                    relations:{model: auth.model}
                },
            };
            nlu.analyze(options).then(responce => {
                resolve(responce.result);
            });
        });
    });
    
}

aggregate();

function aggregate(){
    var analysis = []
    incoming.forEach(tweet => {
        result = analyzeTweet(tweet).then(result => {
            analysis.push(result);
        })
    });
    console.log(analysis);
}

the incoming is irrelevent here

The problem is that when I run the script, I get this output:

[]

What could be wrong or what am I doing wrong. Any concepts do I need to learn in-depth about?

Vedant Jumle
  • 133
  • 2
  • 11
  • 2
    Hi. The results are being built correctly, but the console.log happens synchronously, before the promises have resolved. this question should explain things further [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Félix Adriyel Gagnon-Grenier Sep 09 '20 at 17:18
  • 1
    TLDR; once you're in the promie chain, you stay in the promise chain. – Ayush Gupta Sep 09 '20 at 17:19
  • Yes, I know what the problem is. I know that ```analysis.push(result)``` is in the asynchronous part of the thread. But I want to perform some actions once all the analysis is finished, how do I do that? – Vedant Jumle Sep 09 '20 at 17:28
  • 1
    @VedantJumle in the same function where you do `analysis.push(result);` – Ayush Gupta Sep 09 '20 at 17:48

0 Answers0