JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Monday, ..., Friday, Weekend!</h2>
<ul>
</ul>
JavaScript
getDayPromises() //returns a list of Promises that have already been kicked off
.reduce(function(promiseChain, dayPromise){
return promiseChain.then(function(){
return dayPromise;
})
.then(function(day){
//even if Friday is resolved before Monday, Monday should print out first
print(day);
});
}, Promise.resolve().then(print('Weekend!')));
//reduce produces a single object, which in this case will be a...
/******************************************************************
No need to change anything below this line
*******************************************************************/
function print (msg){
var li = document.createElement('li');
li.innerHTML = msg;
document.querySelector('ul').appendChild(li);
}
function getDayPromises (){
var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
function asyncFetch (msg){
return new Promise(function(resolve, reject){
randomAsync(function(){
console.log("Fetched "+msg);
resolve(msg);
});
});
}
function randomAsync (callback){
var timeout = Math.round(Math.random() * 2000);
setTimeout(callback, timeout);
}
return days.map(asyncFetch);
}