Repetitive Promise in JS
by Matthew Day
JavaScript
function asyncFunc() {
var delay = random(0, 2000);
return new Promise((resolve, reject) => {
console.log('The API Call has been initiated.')
setTimeout(() => {
resolve(delay);
console.log(`Data has been retrieved after ${delay} milliseconds.`)
}, delay);
});
}
asyncFunc()
.then(res => { createArray(res); });
function random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function createArray(number) {
console.log('The API call is complete.');
console.log('- - - - - - - - - - ');
if(number > 1000) {
console.log(`Attempting to make an API call that is faster than ${number} milliseconds`);
var newNumber = random(1, 10);
asyncFunc(newNumber).then(res => { createArray(res) });
} else {
console.log(`Final API call was achieved in ${number} milliseconds`);
}
}