0

I have small problem with my code. Here some pseudo code for understanding:

var array = ["some", "array", "with", "five", "elements"];
Q.all(array.map(async_f1)).then(function(){
    console.log("end");
});

function async_f1(item){
    var deferred = Q.defer();
    // there i'm getting some data from db for each item in array
    var new_array = [array of 100 elements that related to item];
    Q.all(new_array.map(async_f2)).then(function(){
        deferred.resolve();
    });
    return deferred.promise;
}

function async_f2(item){
    var deferred = Q.defer();
    // some operations with item
    if(something == true){
        deferred.resolve();
    }
    return deferred.promise;
}

So how can you see this code is messed up. All functions run in parallel in the same time. After script execution it immediately writes "end" and then executing all the stuff "silent". I want more control and get rid of "nesting". How can I rewrite my code ? Maybe some advises for improving it.

el pax
  • 97
  • 2
  • 8
  • 1
    Avoid the [deferred antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Sep 25 '17 at 20:11
  • "*then executing all the stuff "silent"*" - there's no such thing in the code you posted. Specifically, your `async_f2` does not do anything asynchronous, it looks like you shouldn't even be using promises there. Please post your actual code. Also "*there i'm getting some data from db*" looks sketchy for the same reason, that would likely be an asynchronous operation? – Bergi Sep 25 '17 at 20:12
  • No, you have a loop over an array with a loop over a part of that array item. You cannot get rid of nesting. – Bergi Sep 25 '17 at 20:14
  • As "silent" i mean that all code is "highly" parallel. I want some sync maybe. I want to see every step executed one by one. – el pax Sep 25 '17 at 20:21
  • Well then don't use a loop followed by `Q.all`. Sounds like you want it [sequential](https://github.com/kriskowal/q#sequences), not "sync". – Bergi Sep 25 '17 at 21:13

0 Answers0