0

I have a problem managing promises in a foreach loop.

Here a representation of the code I use :

function FinalFunction() {
    var list = GetList()
    list.forEach(element => {
        console.log('1');
        myFunction();
        console.log('3');
    }
    console.log('4');
}

function First() {
    queryDB().then(
         function (rs) {
             console.log('2');
         }
    );
}

queryDB = function(sql){
    ...
    connectToDB(cfg).then(
        function(){
            ...
        }
    );
    return def.promise;
}

connectoToDb = function(acfg) {
    fb.attach(acfg, 
        function(err,db) {
            ...
        }
    );
    return def.promise;
}

If I have 3 elements in the foreach, in my console I would like

1
2
3
1
2
3
1
2
3
4

But I have

1
3
1
3
1
3
4
2
2
2

With the chain of promises.then first>queryDB>connectToDB I can not set up synchronous with await async.

At what point in my chain should I declare it?

Thank you :) !

Paul Dubois
  • 71
  • 1
  • 1
  • 8

0 Answers0