Async await
/** The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of async and await enables the use of ordinary try / catch blocks around asynchronous code.
async aawait helps us to make code look like synchronous code async makes a function return a Promise , values are wrapped in a resolved promise automatically. await makes a function wait for a Promise ,The keyword await makes JavaScript wait until that promise settles and returns its result.
Letβs emphasize: await literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesnβt cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc. */ function loginUser(username, pass) { return new Promise((resolve, reject) => { setTimeout(function () { resolve({ user: username }); }, 3000); }); }
function getUserPostList(email) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(["post1", "post2"]); }, 2000); }); }
function getPostDetails(postId) { return new Promise((resolve, reject) => { setTimeout(() => { resolve("post details are very long"); }, 3000); }); }
async function display() { const user = await loginUser("username", "pass"); const postList = await getUserPostList(user); const PostDetails = await getPostDetails(postList[0]); console.log("post details are", PostDetails); } display();