If you are involved in Javascript, you probably know about Promises in Async Loop and all related issues. We suppose there are 3 steps of code to reproduce one after the other, all chained. The simple solution could be like this:
function getFlags()
return $.getJSON('https://restcountries.eu/rest/v2/alpha/AR').then(res1 => {
console.log(‘Flag ’+res1.flag);
return $.getJSON('https://restcountries.eu/rest/v2/alpha/CL).then(res2 => {
console.log(‘Flag ’+res2.flag);
return $.getJSON('https://restcountries.eu/rest/v2/alpha/CO).then(res3 => {
console.log(‘Flag ’+res3.flag);
})
})
})
}
To understand more about Java applications read: Node.js Introduction to Understand it
This function will log every message after the request ends. The next request will be executed after that.
That’s ok, but it’s a static way to execute it sequentially. What happens if you have a collection of flags and the only way to do it is by iterating the collection?
This example is not what you want:
function showFlags(flags){
for (let i=0; i < flags.length; i++) {
$.getJSON('https://restcountries.eu/rest/v2/alpha/'+flags[i]).then(res => {
console.log(‘Flag: ’+res.flag)
});
}
}
Because all requests will be fired together and then responded as each one ends.
The solution is BlueBird, a fully featured promise library that allows us to loop a collection. Among other things, it helps us waiting a promise to end.
First install it in your project:
$ npm install --save bluebird
Or
$ bower install --save bluebird
Now look this simple example:
Promise = require("bluebird");
function showFlags(flags){
let allFlags = [];
let allPromises = Promise.each(flags, flag => {
return $.getJSON('https://restcountries.eu/rest/v2/alpha/'+flag).then(res => {
console.log(‘Flag: ’+res.flag);
return true;
});
});
return allPromises;
}
let flags = ['AR', 'CL', 'CO', 'PE'];
showFlags(flags).then(() => {
console.log(‘All flags finished’);
});
You can see more uses on the official web page: http://bluebirdjs.com/docs/features.html
Bluebird overrides the native Promise class to add more functionalities. The method “each” loops throw the flag collection and waits for the return promise inside. Then you have to manage the variable allPromise like a regular promise to log the finished message.
Further reading on Angular framework: why is a good idea to use it?