Running Brain.js Asynchronously Question

I am using Brain.js for some test functions and trying to figure out if I can run it asynchronously from a Function Node. It works fine running synchronously, but the async return function does not seem to fire and output the msg.payload.

Here is my code from the Function Node

var brain=context.global.get('brainjs');

const net = new brain.NeuralNetwork();

var output = [];

const trainingData =[{input: [0], output: [0]},{input: [2], output: [0]},{input: [4], output: [0]},{input: [6], output: [1]},{input: [8], output: [1]},{input: [10], output: [1]}];

net.trainAsync(trainingData, {log: true} )
    .then(res =>{
        //Multiple Outputs
        for(i = 0; i < 10; i++)
        {
            var n = net.run([i]);
            output[i] = "Input: " + i + "  Output: " + n;
        }
        msg.payload = output;
        return msg;
        
    })
    .catch()
    

Maybe as per the docs ? https://nodered.org/docs/user-guide/writing-functions#sending-messages-asynchronously

2 Likes

Added, as per the documentation of asynchronous node msg.
Updated code below seems to work:

var brain=context.global.get('brainjs');

const net = new brain.NeuralNetwork();

var output = [];

const trainingData =[{input: [0], output: [0]},{input: [2], output: [0]},{input: [4], output: [0]},{input: [6], output: [1]},{input: [8], output: [1]},{input: [10], output: [1]}];

net.trainAsync(trainingData, {log: true} )
    .then(res =>{
        //Multiple Outputs
        for(i = 0; i < 10; i++)
        {
            var n = net.run([i]);
            output[i] = "Input: " + i + "  Output: " + n;
        }
        msg.payload = output;
        node.send(msg);//Async MSG
        node.done();
        
    })
    .catch()
    

@tcontrada sir, Can you share your flow as a example