How the *%#! does promise.all() work?

This is a question I had to ask myself many times before discovering the answer. I don’t think it’s that complicated actually, however I do believe that most if not all of the documentation out there is not clear about one key piece of information. So, I am going to try and demystify it here for those of you who haven’t already gotten there yourselves.

var getMoto = function(source) {
return new Promise(function(resolve, reject) {
request('' + source + '&apiKey='+keys, function (error, response, body) {
if (!error && response.statusCode == 200) {
} else {
var getAllMotorcycleArticles = function(req, res) {
var endPoints = ['techcrunch', 'wired-de', 'the-sport-bible', 'techradar', 'reddit-r-all', 'mtv-news-uk', 'google-news', 'fox-sports', 'espn-cric-info'];
var data = [];
endPoints.forEach(function(endpoint) {
.then(function(resp) {
.catch(function(err) {
console.log('wtf!!!', err);

I think what most documentations regarding Promise.all() do not make clear is that you first need to create a function that returns a Promise() . In our case that function is called getMoto() .Then when you push() to your results array you can invoke that function which will return a Promise. Effectively pushing a promise to your results array on each iteration. Then, you can invoke Promise.all() passing in your results array. Which finally gives you access to the asynchronous data in the callback of your .then() function.

This is actual working code from an application I built. Lets walk through it line by line. First I create a function called getMoto() this function takes in one parameter. Which will then be passed in, as a parameter to my http request. Now, inside of getMoto() I return a Promise() which will resolve() the body of my async request.

Now that I have all that lined up, the next step is to loop through my api endpoints array and pass each endpoint into getMoto() . Next push() the Promise that gets returned from getMoto() into the results array. Which is called data here. Then, I invoke promise.all() and pass in data (array of promises) as a parameter. And now, when we say .then() , the async data exist in the callback and all is well.

I hope this clears some things up for some of you. Happy coding!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.