Fun func with promise - step 3

by Julien Roche

HTML

<pre></pre>

Babel + JSX

let preElement = document.querySelector('pre');
let messages = '';
let count = 0;

function addMessage(message) {
	messages += `${message}
`;
	preElement.innerText = messages;
}

function myAsyncFunction (name, timeout = 2000) {
	let id = count + 1;
	count += 1;
  addMessage(`Async function ${count} with name ${name} was called`);
  
	return new Promise(resolve => {
  	setTimeout(() => {
			addMessage(`Async function ${count} with name ${name} was executed`);
			resolve(id);
    
    }, timeout);
  });
}

myAsyncFunction('a', 500)
	.then(() => Promise.all([
  	myAsyncFunction('b', 750),
    myAsyncFunction('c', 250)
	]))
  .then(([ asyncFunctionId1,  asyncFunctionId2]) => {
  	addMessage(`asyncFunctionId1 is ${asyncFunctionId1}`);
    addMessage(`asyncFunctionId2 is ${asyncFunctionId2}`);
    return asyncFunctionId1 * asyncFunctionId2;
  })
  .then((fakeId) => {
  	addMessage(`fakeId => ${fakeId}`);
  })
  .catch(err => {
  	alert('Error !! ' + err);
  });