0

I'm having quite a hard life dealing with this code i wrote.

router.get('*', function(req, res, next) {

    exist.countDocuments(function(err, result){
            if(err) res.send(err)
            else{ 
                console.log('Query Exist Ended: '+result);
                let value = parseInt(result);
                let flag = false;
            let start;
            let end ;
            for (i=0; i<=value; i=i+10){
                console.log(i);
                start=i;
                end=i+9;
                if (end >=value) end = value;
                processItems(start,end); 
            }
            console.log('ENDED...');
            res.end(); 
        }
        
    });

});

I need the cycle to wait for processItems to end, and only then to go ahead... I tried to implement asyncronous function, but maybe i am missing something...

the function processItem is a exist.db query handler. The query execute correctly: I take the number of documents from documentNumber query, and then i call process item that runs a query in partition determined by 'start' and 'end'.

I need it done this way so that i can provide feedback to the user at the end of the operation.

Is there any solution?

Thank you very much.

edit. The console output i have is this: ... 2830 2840 2850 2860 2870

ENDED...

from: 2870to:2874done... from: 2870to:2874done... from: 2870to:2874done... from: 2870to:2874done...

so it cycles all the way through the for loop, and only then it executes the existdb query. the second part of the log is given by processItems

  • Does this answer your question? [How can I wait for set of asynchronous callback functions?](https://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions) – Robert Harvey Nov 30 '20 at 17:36
  • the `.get` (assuming https://api.jquery.com/jquery.get/) returns a promise - you can add `.done(()=> { your code })` to the result - if it's in a function add a `return router.get...` – freedomn-m Nov 30 '20 at 17:36
  • Does this answer your question? [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) – freedomn-m Nov 30 '20 at 17:36

0 Answers0