Rifat Rousseau
Rifat Rousseau

Reputation: 287

How to verify if a for loop completed all iteration in node js, if the loop contains a function call with callback?

I have this snippet of code inside a function.

for(var i = 0; i < common.template1.ROIs.length; i++)
{
    var filename = './data/' + sessionid + '_' + common.template1.ROIs[i].name + '.jpg';
    console.log(filename);
    tesseract.process(filename, options, function(err, text){

    if(err)
    {
        throw err;
    }
        var attr = filename;
        attr = attr.replace('./data/' + sessionid + '_', '');
        attr = attr.replace('.jpg', '');
        retobj[attr] = text;

        console.log(text);

    });
}

res.send(JSON.stringify(retobj));

'retobj' is the global variable, which is initialized as empty objectt, and I want to send it as a response after all the attributes are added inside the for loop. I am new to JS, and found out that it will not work as in other programming language. The callbacks inside for loop are executed asynchronously and a blank object is returned. What is the proper way of sending back the retobj and to find out if all the callbacks have been completed? Thanks in advance.

Upvotes: 0

Views: 835

Answers (1)

Drifter
Drifter

Reputation: 281

An ugly but simple way:

var loopsFound = common.template1.ROIs.length,
    allowSend = loopsFound;

function sendRetObj(){
    allowSend--;
    if(allowSend < 1){
        res.send(JSON.stringify(retobj));
    }
}

for(var i = 0; i < loopsFound; i++)
 {
    var filename = './data/' + sessionid + '_' + common.template1.ROIs[i].name + '.jpg';
    tesseract.process(filename, options, function(err, text){

        try {
            if(err)
            {
                throw err;
            }


           var attr = filename;
           attr = attr.replace('./data/' + sessionid + '_', '');
           attr = attr.replace('.jpg', '');
           retobj[attr] = text;
        }
        catch(err){
            throw err;
        }
        finally{
             sendRetObj();
        }

    });
}

Upvotes: 1

Related Questions