Last active
September 15, 2020 19:41
-
-
Save thebeebs/cd7bb47ecb8f6695b5f4e77c276e185d to your computer and use it in GitHub Desktop.
An example of using Async Await to create some text in a guaranteed order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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