Javascript Tutorial: Recursive Promise Calls
The Reason
So in trying to help a co-worker I was looking for an example of how you can do recursive promise calls. To my surprise I didn’t find any soooo now you get this post 🙂 In a typical scenario you would chain your promises one after the other, however in real world situations the solution is not always so cut and paste. For instance you may need to ping a crappy device and wait for the results of the first ping to come back before you can ping the device again. If that’s the case upgrade your device, but if that’s not an option then you can always use this slash and hack solution of recursive promise calls which I would not recommend unless you have to but yeah, real life sucks sometimes. So here you have it, I hope this helps.
Test or fork the working example on Plunker
The Code
//somewhere to store the results of your recursive calls var results = []; /** * Recursive function * * @param int val how many times to call this function recursively * @return null **/ var promiseMore = function(val) { console.log('attempting promise ' + val); //defer the promise var deferred = Promise.defer(); //check your recursive conditions, keep looping while true if (val > 0) { //run your ajax request $.ajax({ method: 'post', url: 'https://api.random.org/json-rpc/1/invoke', data: JSON.stringify({ "jsonrpc": "2.0", "method": "generateSignedStrings", "params": { "apiKey": "4e69c4a7-4e47-4811-b110-6c7bfce079db", "n": 1, "length": 4, "characters": "abcdefghijklmnopqrstuvwxyz", "replacement": true }, "id": 29970 }), dataType: 'json', success: function(response) { document.write('Got data for promise ' + val + '<br/>'); results.push(response.result.random.data[0]); //this triggers the recursion d = promiseMore(--val); //resolve this promise return deferred.resolve(d); } }); } else { doSomethingWithResults(); } } /** * Whatever you want to do when your recursive promises are done firing * * @return null * @print lots of BS random string results from our promises **/ var doSomethingWithResults = function() { document.write('<br/>============<br/>'); document.write('Doing something with the results now...'); document.write('<br/>============<br/><br/>'); //print out the data we got from the recursive promises for (i = 1; i <= results.length; i++) { document.write('Results ' + i + ': ' + results[i-1] + '<br/>'); } } //kick off the call to the recrusive promises promiseMore(10);