Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An example of using Async Await to create some text in a guaranteed order.
// Calling the function using promises.
addElement("first promise sexy syntax")
.then(x => addElement("second promise syntax"))
.then(x => addElement("third promise syntax"))
.then(x => addElement("fourth promise syntax"))
// Calling the function using Async/Await
async function myFunction(){
await addElement("first async");
await addElement("second async");
await addElement("third async");
await addElement("forth async");
};
myFunction();
// A demo function that will take a random time to create a H1 element
function addElement(elementText){
return new Promise(function(resolve,reject){
setTimeout(function(){
var element=document.createElement('H1');
element.innerText = `${elementText} ${Date.now()}`;
document.body.appendChild(element);
resolve();
}, Math.random() * 2000);
})}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment