// Note IE11 does not support Promise needs a polyfill
function print(s) {
$('p').append(s);
//document.write(s);
}
function f1() {
return new Promise(function(resolve, reject) {
print('f1<br>');
resolve();
});
}
function f2() {
return new Promise(function(resolve, reject) {
print('f2<br>');
resolve();
});
}
function fn(s) {
var pf = function(resolve, reject) {
var f = function() {
print(s + '<br>');
resolve();
};
var t = Math.round(Math.random() * 1000);
setTimeout(f, t);
};
var p = new Promise(pf);
return p;
}
function done() {
print('done<br>');
}
function test1() {
f1().then(f2).then(done);
}
function test2() {
fn('f3').then(done);
}
function test3() {
var p = [];
var n = 2;
for (var i = 0; i < n; ++i)
p.push(fn('f' + i));
}
function test4() {
var p = Promise.resolve();
var n = 10;
// this is async
//for (var i = 1; i <= n; i++)
// p = p.then(fn(i));
// sync works with es6 => may not be supported by IE11
//for (let i=1; i<=10; i++)
// p = p.then(() => fn(i)); // es6
var promises = []
for (var i=1; i<=n; i++) {
var pr = fn.bind(null, i);
p = p.then(pr);
promises.push(p);
}
// Can do either Promises.all or p.then
//p.then(done);
// Advantage of Promises.all is it work for zero promises also
Promise.all(promises).then(done);
print('Finished creating promises<br>');
}
//test1();
//setTimeout(test2, 500);
//test3();
test4();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.