请选择 进入手机版 | 继续访问电脑版

技术控

    今日:35| 主题:61447
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Async / Await Warm Up

[复制链接]
ζ扯蛋的夏天 发表于 2016-12-2 05:52:42
118 4

Async / Await Warm Up

Async / Await Warm Up-1-技术控-javascript,beginning,function,anything,because
       Async / Await Warm Up

   If you’re used to using Promises, async / await is an elegant way to make your javascript more legible. It reads as synchronous code but evaluates on the next microtask .
   Let’s jump right in and poke around. Open up the babel repl and code along with me. Take a simple function and add async to the beginning:
  1. async function sayHello() { return 'hello';}
复制代码
  1. console.log(sayHello()); // => Promise {}
复制代码
  You’ll see that calling this function returns a Promise rather than “hello”. This is because anything returned from an async function is automatically wrapped in a promise. In order to log “hello” we could do this:
  1. sayHello()  .then(str => console.log(str)) // => 'hello'
复制代码
OK so what about await?

  First, write a function that returns a promise:
  1. function mapLater(arr, fn, time) {  return new Promise((resolve, reject) => {    setTimeout(() => {      resolve(arr.map(fn));    }, time);  });}
复制代码
  Pretty straight forward, we map over an array after given amount of time. Now let’s use that in an async function.
  1. async function addAndMultiply(arr) {  const added = await mapLater(arr, i => i + 2, 2000);  const multiplied = await mapLater(added, i => i * 2, 2000);    console.log(multiplied);}
复制代码
  1. addAndMultiply([1, 3, 6, 20]); console.log('hello')
复制代码
  1. // => 'hello'// 4 secs later => [6, 10, 16, 44]
复制代码
  You’ll see that “hello” is logged before we are returned our array. Our async function is non-blocking.
   It’s important to note that await must always be inside of an async closure. Calling it in the global scope or in a function without the the async keyword will throw an error.
  Handling errors

   Imagine something goes wrong with our original mapLater function:
  1. ...setTimeout(() => {  reject('nope');}, time);
复制代码
  Currently, we have no way of surfacing the error in our async addAndMultiply function. When we run it, the function will fail silently. To handle errors, one solution is to use try / catch :
  1. async function addAndMultiply(arr) {  try {    const added = await mapLater(arr, i => i + 2, 2000);    const multiplied = await mapLater(added, i => i * 2, 2000);    console.log(multiplied);   } catch(err) {    console.error(err); // 2 secs later => 'nope'  }}
复制代码
Since errors bubble up by default, another practical solution would be to handle errors at the async entry point:
  1. intricatelyNestedAsyncFunc().catch(err => console.error(err));
复制代码
Real World

   Use it today! So many great libraries provide APIs that return promises. For example, if you’re using  fetch  to retrieve data, you can start doing things like:
  1. console.log(sayHello()); // => Promise {}0
复制代码
  To use async / await now  you’ll need to use Babel’s  transform-async-to-generator  .
拾忆Dreams 发表于 2016-12-4 03:48:30
今天没事来逛逛
回复 支持 反对

使用道具 举报

情流感 发表于 2016-12-5 11:21:16
看在ζ扯蛋的夏天的面子上,认真回帖!
回复 支持 反对

使用道具 举报

那些似相识 发表于 2016-12-5 12:30:15
回复不是我的目的!
回复 支持 反对

使用道具 举报

tmqp3wVe 发表于 2016-12-15 22:24:58
为何我的眼中总饱含泪水?因为我装逼装得深沉。
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表