0

I'm new with promises and I don't know how to do this. The thing is that I will have a number of elements, and for each I will call a function that has a callback. When all this callbacks had been executed I want to execute another function. Something like this:

var elements = [e1,e2, ...] //I don't know how many will be

for (var i = 0; i < elements.length; i++) {
    functionWithCallBack(elements[i] ,function(){
        //some magic
    })
}

//When all the callbacks had been executed I want to execute this one
var finally = function(i){
    //some code
}

I know that the solution is with promises, but I just can't get how to do it. Any advice?? Thanks in advance!!

joacoleza
  • 775
  • 1
  • 9
  • 26
  • You'll have to edit all the functions so they return promises instead of using callbacks – adeneo Nov 16 '16 at 20:40
  • It's not possible. The function is in a minified js which I cannot edit – joacoleza Nov 16 '16 at 20:43
  • Then how would you know when the callback functions have completed, assuming it's async? If it's all synchronous, you don't need promises – adeneo Nov 16 '16 at 20:44
  • The truth is I do not know if it is asynchronous. But how can I do it? Nesting each new call inside the callback of the previous one? – joacoleza Nov 16 '16 at 20:47
  • Make one deferred per function call ([promisify](http://stackoverflow.com/q/22519784/1048572) the function separately) and then [wait for the array of deferreds](http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when?rq=1). – Bergi Nov 16 '16 at 20:49
  • ^ that's one way to do it, would look like -> https://jsfiddle.net/83n3bgvL/ – adeneo Nov 16 '16 at 20:52
  • Take a look at `Promise.all()` – Barmar Nov 16 '16 at 21:12

0 Answers0