Asynchronous recursive using promises

So, I try to transfer my code to the "world of promises", and in many cases when I had to "go in cycles" with asynchronous functionality - I just used recursion in this way

function doRecursion(idx,callback){ if(idx < someArray.length){ doAsync(function(){ doRecursion(++idx,callback) }); }else{ callback('done!') } } doRecursion(0,function(msg){ //... }); 

Now I'm trying to make a difference in the world of promises, and I'm pretty stuck

 var Promise = require('bluebird') function doRecursion(idx){ return new Promise(function(resolve){ if(idx < someArray.length){ doAsync(function(){ //... doRecursion(++idx) // how do i call doRecusion here.... }); }else{ resolve('done!') } }); } doRecursion(0).then(function(msg){ //... }); 

Thanks.

+5
source share
2 answers

I would go with the Promise.all approach.

What does this mean, wait until all promises in the array are resolved. The map will apply the async method to each element of the array and return a promise.

 function doAsyncP() { return new Promise((resolve) => { doAsync(function() { resolve(); }); }); } Promise.all( someArray.map(doAsyncP) ).then((msg) => { //we're done. }); 
+4
source

In your recursive function, you can do this:

 ... if (idx < someArray.length) { doAsync(function() { resolve(doRecursion(idx + 1)); }); } else { ... 

In other words, although idx less than someArray.length , your promise will resolve another promise, this time the promise is returned by calling doRecursion() with idx incremented by one. then lower callback will not be called until doRecursion resolves any value other than the promise. In this case, it will eventually resolve with the value 'done!' .

However, if you use promises, you probably won't need to use recursion at all. You may need to reorganize your code a bit more, but I would suggest considering the @BenFortune option as an alternative.

+1
source

Source: https://habr.com/ru/post/1243575/


All Articles