技术控

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

[其他] Async / Await Warm Up

[复制链接]
ζ扯蛋的夏天 发表于 前天 05:52
22 1

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

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:
  [code]async function sayHello() { return 'hello';}[/code]  [code]console.log(sayHello()); // => Promise {}[/code]   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:
  [code]sayHello()  .then(str => console.log(str)) // => 'hello'[/code]  OK so what about await?

  First, write a function that returns a promise:
  [code]function mapLater(arr, fn, time) {  return new Promise((resolve, reject) => {    setTimeout(() => {      resolve(arr.map(fn));    }, time);  });}[/code]   Pretty straight forward, we map over an array after given amount of time. Now let’s use that in an async function.
  [code]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);}[/code]  [code]addAndMultiply([1, 3, 6, 20]); console.log('hello')[/code]  [code]// => 'hello'// 4 secs later => [6, 10, 16, 44][/code]   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:
  [code]...setTimeout(() => {  reject('nope');}, time);[/code]   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 :
  [code]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'  }}[/code]  Since errors bubble up by default, another practical solution would be to handle errors at the async entry point:
  [code]intricatelyNestedAsyncFunc().catch(err => console.error(err));[/code]  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:
  [code]console.log(sayHello()); // => Promise {}0[/code]   To use async / await now  you’ll need to use Babel’s  transform-async-to-generator  .
友荐云推荐




上一篇:How Developers Are Responding to Ethereum's Unexpected Fork
下一篇:Front End Optimization – 9 Tips to Improve Web Performance
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

拾忆Dreams 发表于 12 小时前
今天没事来逛逛
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表