basic promise example

basic promise so you can learn how to use them.

by Adam Kinnucane

HTML

<div class="world">

</div>

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}

JavaScript

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code. 
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 2500);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  element = document.querySelector(".world");
  element.innerHTML =("Yay! " + successMessage);
});

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
// https://developers.google.com/web/fundamentals/primers/promises#whats-all-the-fuss-about


// chained promise example
function cleanRoom(){
	return new Promise(function (resolve,reject){
		resolve('Cleaned the room');
	})
}

function removeGarbage(promise) {
	return new Promise(function(resolve,reject){
		resolve('remove the garbage');
	})
}

function winIcecream(promise) {
	return new Promise(function(resolve,reject){
		resolve('won IceCream');
	})
}

// call the start of the chain
cleanRoom().then(() =>{
// return the next functions promise
	return removeGarbage();	
}).then(() =>{
// return the next function promise
	return winIcecream();
// message to prove it worked.
}).then(() =>{
	document.querySelector("#app").innerHTML = "finished the promise chain";
});