Hi everyone,
I am currently trying to get to grips with the syntax for ES6 promises and Async / Await.
I have some code like so:
HTML
<button class="selector">CLICK ME</button>
JS
var selector = document.querySelector('.selector');
function f1() {
selector.addEventListener('click', () => {
f2();
});
}
function f2() {
setTimeout(() => {
console.log('initial click')
}, 3000);
f3();
}
function f3() {
alert('clicked');
}
f1();
How do I set this up using promises or async await so that f3() does not start until f2() is finished?
async / await is just syntactic sugar that is built on top promises to make asynchronous responses feel more synchronous (but they are still async), so first and foremost Iād learn how to create a function that returns a promise. The basic structure of doing so is
function myPromise(){
return new Promise(function(resolve,reject){
// if the async action goes well wrap your data in the resolve argument of the callback
resolve(data)
// if the async action does not go well wrap your data in the reject argument of the callback
reject(error)
})
}
then, to unravel your promise you have 2 ways (and this is where async/await can be used)
- the regular
.then()
way, (if you have a bunch of promises then you could use Promise.all
)
myPromise()
.then(data => console.log(data)) // if the async action is successful you will get your data here
.catch(error => console.log(error)) // if the async action is unsuccessful you will get your error here
- the async/await way
async function myAsync(){
try{
const data = await myPromise();
// you can chain as many more functions that return promises here
// and they will be executed sequentially
console.log(data)
}catch{
console.log(e)
}
}
myAsync()
So, try wrapping your functions using the structure above and post them here if you come across any issues.
2 Likes
Thanks so much for the answers above guys. I managed to work out my problem!