Async await syntax
Course: Promises and async, await - chapter 7
The async and await syntax in JavaScript provides a way to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain.
It builds on top of Promises and allows you to avoid chaining .then() and .catch() methods while still working with asynchronous operations.
async/await is essentially syntactic sugar on top of Promises.
Assignment
Section titled “Assignment”Write code that
- logs
hiafter 1 second - logs
hello3 seconds afterstep 1 - logs
hello there5 seconds afterstep 2
function setTimeoutPromisified(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
async function solve() { await setTimeoutPromisified(1000); console.log("hi"); await setTimeoutPromisified(3000); console.log("hello"); await setTimeoutPromisified(5000); console.log("hi there");}
solve();Things to keep in mind
Section titled “Things to keep in mind”- You can only call
awaitinside a function if that function isasync - You cant have a
top level await