promise boy making lots of promises |
Code example of making multiple promises in javascript with the requirement of resolving once all promises are completed, as well as handling when one of them fails.
In this case, making separate calls to a dummy service which can failed 10% of the time, and either showing the results of the calls or gracefully stopping if a rejection occurs.
// This is an example of an api call that will
// return a success or fail after 1 to 5 seconds
function apiget_dummy(url) {
return new Promise(function(resolve, reject) {
setTimeout(y = function () {
if (Math.random() < 0.1) {
console.log('(api) url failed')
reject(url + ' failed')
return;
}
console.log('(api) url success')
resolve('This is a successful response');
}, 1000 + Math.random() * 4000);
})
}
urls = ['www.example.com/myfirstapi/test?query=5', 'www.example.com/doesthiswork', 'www.example.com']
Promise.all(
urls.map(url => { return apiget_dummy(url); })
).then((values) => {
console.log('This code will run successfully once all urls are processed');
console.log(values);
}).catch(reasons => {
console.log('Oh no! This code failed because one of the urls was rejected');
console.log(reasons);
});
This makes use of Promise.all to take multiple promises and handle them, as well as the map function to declare an array of function calls.
You can run this in your console to see it working!