1. Trang chủ
  2. » Công Nghệ Thông Tin

The evolution of javascript asynchronous calls

22 139 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Slide 1

  • Agenda

  • JS is single-threaded

  • The innocent Callback

  • jQuery callback style

  • Callback hells

  • The downside

  • 2. Promise all the things

  • Resolve and reject

  • Chaining promises

  • How promise solve callback hell

  • So you want parallel call?

  • Pitfall (Promise hell and error handling)

  • Why promise

  • Let’s rest for 20 seconds

  • The magic of async/await (ES7)

  • Make asynchronous code easy again

  • Magic time, oops… demo time

  • Everything look … synchronous

  • How about old browsers?

  • Looking back

  • Thank you for listening!

Nội dung

The Evolution of JavaScript Asynchronous Calls Pham Huy Hoang - Harry Pham Github: conanak99 Agenda How we deal with asynchronous call in JS Innocent Callback and callback hell Promise all the things The magic of async/await JS is single-threaded ● JS has a single Call Stack => Can only one thing at a time ● While the Call Stack has functions to execute, the browser can’t actually anything else  => Browser hang and laggy UI ● Solution: Asynchronous Call This demo will hang the browser 1.The innocent Callback ● Functions are first-class objects ● We can pass a function as an argument in another function ● Later execute that passed-in function at convenience time jQuery callback style $(docum ent).ready(function() { $('# button').on('click',function(event) { $.getJSO N ('/data.json',function(data) { console.log(data); }); }); }); D em o: https://codepen.io/huyhoangpham/pen/veGYrw?editors=1010#0 Callback hells getD ata(function(a) { getM oreD ata(function(b) { getM oreD ata(function(c) { getM oreD ata(function(d) { getM oreD ata(function(e) { // som ething }); }); }); }); }) https://codepen.io/huyhoangpham /pen/V M aYw o?editors= 1010 The downside ● Make code difficult to maintain and debug ● Exception handling is … tedious ● Anonymous inline function = hard-to-read call stack Promise all the things ● Represents the eventual result of an asynchronous operation ● Must be in one of three states: pending, fulfilled, or rejected Resolve and reject const prom ise = new Prom ise((resolve,reject) = > { const prom ise = new Prom ise((resolve,reject) = > { // async stuf f // async stuff resolve('D O N E!'); reject(new Error('FAIL!')); }); }); prom ise.then((result) = > { prom ise console.log(result); // result w illbe 'D O N E!' }); then((result) = > { // W illnot be called }) D em o: https://codepen.io/huyhoangpham /pen/gG rbM M ?editors= 1010 catch((error) = > { console.log(error); // FAIL! }) Chaining promises function getD ata(input) { return Prom ise.resolve(input + 'data'); } getD ata('hello') then((result) = > { throw new Error('O ops'); }) getD ata('hello') then((result2) = > { then((result) = > { return result + 'chain prom ise'; // result: 'hello data' }) then((result2) = > { return result2; }) then((result3) = > { return result3; console.log(result2); }) // result2: 'hello data chain prom ise' catch((error) = > { }) D em o: https://codepen.io/huyhoangpham /pen/G M Zgrq?editors= 1010 console.log(error); //oops }) How promise solve callback hell getD ata(function(a) { getD ata() getM oreD ata(function(b) { then(getM oreD ata) getM oreD ata(function(c) { then(getM oreD ata) getM oreD ata(function(d) { then(getM oreD ata) getM oreD ata(function(e) { then(getM oreD ata) // som ething }); }); }); }); }) then((result) = > { // som ething }) catch((error) = > { handleError(error); }); So you want parallel call? Prom ise.all([ fi rstAsyncC all(), secondAsyncC all(), lastAsyncC all(), ]) then(result = > { fi rstAsyncC allResult = result[0]; secondAsyncC allResult = result[1]; lastAsyncC allResult = result[2]; }); D em o: https://codepen.io/huyhoangpham /pen/YrqPVy?editors= 1010 Pitfall (Promise hell and error handling) getD ata.then(() = > { prom ise.then(resolve,reject); getM oreD ata.then(()= > { getM oreD ate.then(() = > { // D o som ething }); }); }); prom ise.then( (result) = > { // D o som ething throw new Error('This error w illnot be caught'); }, (error) = > { console.log(error); }); Why promise ● Cleaner method signatures -> Easier to read ● Easier to write function and test -> Reduce cost of maintenance ● It allows for chaining of promises -> Clear and shorter code Let’s rest for 20 seconds The magic of async/await (ES7) Treat functions returning Prom ise objects as if they w ere synchronous $('# request').click(async () = > { const im gU rl= aw ait fi n dRandom Im gProm ise('cat'); $('# cat').attr('src', im gU rl); }); https://codepen.io/huyhoangpham/pen/aLNzLr?editors=1010 Make asynchronous code easy again async function doG reatThing() { getD ata(function(a) { try { getM oreD ata(function(b) { getM oreD ata(function(c) { getM oreD ata(function(d) { getM oreD ata(function(e) { // som ething const fi rstD ata = aw ait getD ata(); const secondD ata = aw ait getM oreD ata(fi rstD ata); const thirdD ata = aw ait getM oreD ate(secondD ata); // H ow about parallelcall? const saveResults = aw ait Prom ise.all([ saveD ata(fi rstD ata), }); saveD ata(secondD ata), }); saveD ata(thirdD ata)]); }); } catch (error) { }); console.log(error); }) } } Magic time, oops… demo time ● Sequential: https://codepen.io/huyhoangpham/pen/VMaYxe?editors=1010 ● Parellel: https://codepen.io/huyhoangpham/pen/JrXdXK?editors=1010 ● Looping: https://codepen.io/huyhoangpham/pen/rGeaXX?editors=1010 Everything look … synchronous ● Await keyword is only available in a async function ● No more callback, then, or catch => Cleaner code ● Easier to debug ● Easy looping and error try/catch => Everything look … synchronous How about old browsers? ● Use babel transpiler ● Behind the scene: ● Generate a state machine Looking back We have came a long way ● From Callback to Promise(ES6) to Async/Await(ES7) ● Callback is still used for event, but should not for asynchronous call ● Should have a good understanding on Promise ● Use async/await if possible It makes our life better JS Code Combo Use bluebird to turn callback into promise Use the magic of async/await Thank you for listening! ... ● While the Call Stack has functions to execute, the browser can’t actually anything else  => Browser hang and laggy UI ● Solution: Asynchronous Call This demo will hang the browser 1 .The innocent... and error handling) getD ata.then(() = > { prom ise.then(resolve,reject); getM oreD ata.then(()= > { getM oreD ate.then(() = > { // D o som ething }); }); }); prom ise.then( (result) = > { // D... cost of maintenance ● It allows for chaining of promises -> Clear and shorter code Let’s rest for 20 seconds The magic of async/await (ES7) Treat functions returning Prom ise objects as if they

Ngày đăng: 20/11/2017, 22:07

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN

w