Promises: Sequential Request Pattern
Promises
by nickadeemus2002
JavaScript
var fetch = require('node-fetch');
var endpoints = [
{ name: "people", url: "http://swapi.co/api/people/"},
{ name: "planets", url: "http://swapi.co/api/planets/"},
{ name: "films", url: "http://swapi.co/api/films/"},
{ name: "species", url: "http://swapi.co/api/species/"},
{ name: "vehicles", url: "http://swapi.co/api/vehicles/"},
{ name: "starships", url: "http://swapi.co/api/starships/"}
];
var prepareData = function (){
var storedData = [];
return {
add: function (resData) {
return storedData.push(resData);
},
getAll: function () {
return storedData;
}
};
}();
// Build a sequential chain of
// promises from array elements
function sequence(array, callback) {
return array.reduce(function chain(promise, item) {
return promise
.then(function () {
return callback(item);
});
}, Promise.resolve());
};
function getInfo(endpoint) {
console.log('##################################################');
console.log('Requested info for ' + endpoint.name);
console.log('##################################################');
return fetch( endpoint.url, { method: 'GET'})
.then(function(res) {
return res.json();
});
}
/**
* Business Logic
*/
sequence(endpoints, function (endpoint) {
// get data from all endpoints in a
// a order defeined by array, then
// return a promise
return getInfo(endpoint)
.then(function (info) {
prepareData.add(info);
});
})
.then(function(){
// all data is stored, now we can
// tranform values
console.log("getAll stored data: -> ", prepareData.getAll());
})
.catch(function (reason) {
console.log(reason);
});