<!DOCTYPE html> Async await class: center, middle # Quick(ish) Introduction to Async Await --- # Agenda 1. Promises 2. Some examples 3. Async-Await --- # Brief introduction to promises ```js const p = new Promise( function (resolve, reject) { // (A) // this runs when promise is created if (···) { resolve(value); // success } else { reject(reason); // failure } }); ``` ![Right-aligned image](https://bilaldurrani.io/presentations/async-await/assets/images/promise-resolve-reject.png) ??? Promise is a one shot thing. There are two states. --- # The Promise body executes immediately ```js let promise = new Promise(function(resolve, reject) { // the function is executed automatically when the promise is constructed alert(resolve); // function () { [native code] } alert(reject); // function () { [native code] } // after 1 second signal that the job is done with the result "done!" setTimeout(() => resolve("done!"), 1000); }); ``` --- # Passing values thru promises ```js asyncFunc() .then(function (value1) { return 123; }) .then(function (value2) { console.log(value2); // 123 }); ``` Here we pass back a regular value --- # Chaining multiple promises You can do this ```js asyncFunc1() .then(result1 => { asyncFunc2() .then(result2 => { ··· }); }); ``` --- # Chaining promises This is a bit nicer ```js asyncFunc1() .then(function (value1) { return asyncFunc2(); }) .then(function (value2) { ··· }) ``` --- # Chaining promises Or even this ```js asyncFunc1() .then(asyncFunc2) .then(asyncFunc3) ``` --- # Error handling with Promises ```js var jsonPromise = new Promise(function(resolve, reject) { // JSON.parse throws an error if you feed it some // invalid JSON, so this implicitly rejects: resolve(JSON.parse("This is sucky JSON")); }); jsonPromise.then(function(data) { // This never happens: console.log("It worked!", data); }).catch(function(err) { // Instead, this happens: console.log("It failed!", err); }) ``` --- # What will you see when you run this? ```js // an immediately resolved promise let promise = new Promise(resolve => resolve("done!")); promise.then(alert); ``` --- # What will you see when you run this? ```js // an immediately resolved promise let promise = new Promise(resolve => resolve("done!")); promise.then(alert); alert('code finished'); ``` -- You will see an alert with `code finished`, followed by a plain alert `then` handlers are asynchronous. --- # What is the bug here? ```js function foo() { const promise = asyncFunc(); promise.then(result => { }); return promise; } ``` -- We need to return the result of the `then()`. --- # Examples ```js function doubleAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x * 2); }, 2000); }); } doubleAfter2Seconds(10).then((r) => { console.log(r); }); ``` --- # Slightly more complicated example What if we wanted to pass multiple values? ```js let sum = doubleAfter2Seconds(10) + doubleAfter2Seconds(20) + doubleAfter2Seconds(30); console.log(sum); ``` --- # Slightly more complicated example What if we wanted to pass multiple values? ```js let sum = doubleAfter2Seconds(10) + doubleAfter2Seconds(20) + doubleAfter2Seconds(30); console.log(sum); ``` This won't work. --- # Slightly more complicated example What if we wanted to pass multiple values? ```js function addPromise(x){ return new Promise(resolve => { doubleAfter2Seconds(10).then((a) => { doubleAfter2Seconds(20).then((b) => { doubleAfter2Seconds(30).then((c) => { resolve(x + a + b + c); }) }) }) }); } ``` Welcome to callback hell, again... --- # Slightly more complicated example What if we wanted to pass multiple values? ```js async function addAsync(x) { const a = await doubleAfter2Seconds(10); const b = await doubleAfter2Seconds(20); const c = await doubleAfter2Seconds(30); return x + a + b + c; } ``` --- # Async This is a simple async function. ```js async function f1() { return Promise.resolve(1); } async function f2() { return 1; } f().then(alert); ``` -- `f1` and `f2` are the same thing. Async functions *always* return a `Promise`. --- # Await `await` can only used in async function. --- # No top level async 😣 Have to wrap it in an IIFE if using in Node ```js ( async() => { await blah(); })(); ``` --- # Error Handling ```js async function f() { await Promise.reject(new Error("Whoops!")); } ``` -- Is the same as this ```js async function f() { throw new Error("Whoops!"); } ``` --- # Error Handling Just use try/catch. No `catch()` needed. ```js try{ await f(); } catch (err) { alert(err); } ``` --- # Resources [Promises](http://exploringjs.com/es6/ch_promises.html#sec_three-ways-understanding-promises) [Async/Await](https://javascript.info/async-await)

4 min · 690 words · Bilal Durrani