Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Last active August 31, 2016 09:37
Show Gist options
  • Save VivienAdnot/4bca969a06d1c73638a5d639f0501eb4 to your computer and use it in GitHub Desktop.
Save VivienAdnot/4bca969a06d1c73638a5d639f0501eb4 to your computer and use it in GitHub Desktop.
Play with promises: call several endpoints and aggregate the result
var data = [{
isActive: "1",
logins: 2000,
clicks: 1000
}, {
isActive: "1",
logins: 3000,
clicks: 1000
}, {
isActive: "1",
logins: 1000,
clicks: 1000
}];
var result = 0;
var timeouts = [0, 2000, 4000];
var callApi = function(index, timeout) {
return new Promise(
function(resolve, reject) {
window.setTimeout(function() {
resolve({
data: data[index]
});
}, timeout);
}
);
};
timeouts.forEach(function(timeout, index) {
callApi(index, timeout)
.then(function(res) {
result += res.data.logins;
console.log(index + " - result: " + result);
});
});
const data = [{
isActive: "1",
logins: 1000,
clicks: 1000
}, {
isActive: "1",
logins: 2000,
clicks: 1000
}, {
isActive: "1",
logins: 3000,
clicks: 1000
}];
const callApi = (index, timeout) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve({
data: data[index]
}), timeout);
})
};
let result = 0;
[0, 3000, 0].forEach((timeout, index) => {
callApi(index, timeout)
.then(res => {
result += res.data.logins
console.log(`Result now in callback ${index + 1}:`, result)
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment