Skip to content

Instantly share code, notes, and snippets.

@rpbeltran
Created December 18, 2016 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpbeltran/26679dc3beb5d619c46ed69d3a35bf8a to your computer and use it in GitHub Desktop.
Save rpbeltran/26679dc3beb5d619c46ed69d3a35bf8a to your computer and use it in GitHub Desktop.
Times Promise
// Times Promise
// By: Ryan Beltran
function times(t) {
return new Promise(function (resolve) {
for (var i = 0; i < t; i++) {
resolve();
}
});
}
Promise.times = function (fn, t) {
if (!t) {
t = fn;
fn = function () {};
}
var promise = times(t);
for (var i = 0; i < t; i++) {
promise = promise.then(fn);
}
return promise;
}
Promise.prototype.times = function (fn, t) {
return this.then(function () {
return Promise.times(fn, t);
});
}
@rpbeltran
Copy link
Author

Example Usage:

// Logs the number 1 once, the number 2 twice, number 3 three times, and so on through 5 
Promise.resolve()
	.times( function(){console.log(1)}, 1 )
	.times( function(){console.log(2)}, 2 )
	.times( function(){console.log(3)}, 3 )
	.times( function(){console.log(4)}, 4 )
	.times( function(){console.log(5)}, 5 );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment