Last active
August 31, 2016 09:37
-
-
Save VivienAdnot/4bca969a06d1c73638a5d639f0501eb4 to your computer and use it in GitHub Desktop.
Play with promises: call several endpoints and aggregate the result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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