Web前端之路

为ES2015解构干杯

2017-03-21  本文已影响525人  熊二不大

我认为ES2015解构语法相当酷炫。他虽然没有像Promises,Generators以及Class语法那么上镜头,但是我发现它非常有用。你也可以阅读这里里面非常详细讲解了它。
唯一的遗憾是,大部分的例子我发现仅仅关注语法层面,而不是实际应用当中。像这个从MDN文档中的取的例子:

var a, b;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

幸运的是我有一些真实场景使用解构语法案例给你们分享!

保持Promises化

一个我最喜欢使用解构的是当使用Promise.all等待一系列异步任务全部完成时候。Promise.all返回值是以数组形式返回,而我们一般迭代数组取出里面的值,根据自己的需要才能操作这些值。
但是如果你知道使用解构获取你期望的对象,会让你的生活变得轻松和代码变得更漂亮,更多的描述性的命名参数。请看一个例子

啤酒比较

比方说你要比较两个brewDog的美味啤酒什么的,有时候我发现在现实生活中一直做这种事情。我们可以从sam Mason的美妙的Punk API获取关于啤酒信息。我们通过fetchAPI从上面API获取不同啤酒数据。我们比较啤酒℃之前,我们需要先发起这两个请求。
让我们一起先看下代码:

const punkAPIUrl = "https://api.punkapi.com/v2/beers/106";
  const deadPonyClubUrl = "https://api.punkapi.com/v2/beers/91";
  const punkAPIPromise = fetch(punkAPIUrl)
    .then(res => res.json())
    .then(data => data[0]);
  const deadPonyClubPromise = fetch(deadPonyClubUrl)
    .then(res => res.json())
    .then(data => data[0]);

  Promise.all([punkAPIPromise, deadPonyClubPromise])
    .then(beers => {
      const punkIPA = beers[0];
      const deadPonyClub = beers[1];
      const stronger = (punkIPA.abv < deadPonyClub.abv ? deadPonyClub.name : punkIPA.name) + " is stronger";
      console.log(stronger);
    });

我们使用参数解构整理一下Promise

 Promise.all([punkAPIPromise, deadPonyClubPromise])
    .then(([punkIPA, deadPonyClub]) => {
      const stronger = (punkIPA.abv < deadPonyClub.abv ? deadPonyClub.name : punkIPA.name) + " is stronger";
      console.log(stronger);
    });

我们知道我们获取两个啤酒的结果,这个例子的结构让我知道那个啤酒的结果是那个啤酒的,所以我们可以使用解构参数来命名,而不是通过数组来提取他们。

更多例子

好吧,这可能仍然是一个弥补的例子,但它肯定更接近现实生活。第一次,我发现自己使用这种技术是在写Service Workers for 12 Devs of Christmas这篇文章的时候。它写得很方便,当returnFromCacheOrFetch使用cachesfetchAPI 实现“stale while revalidate”缓存方法。
该方法执行缓存方法,并尝试将当前请求与缓存匹配。在返回之前,它然后启动对fetch请求的资源的请求,缓存结果。最后,如果在缓存中找到请求,则返回缓存的响应,否则返回新的获取请求。你可以在原始的博客文章中阅读更多。
最终代码如下:

function returnFromCacheOrFetch(request, cacheName) {
  const cachePromise = caches.open(cacheName);
  const matchPromise = cachePromise
    .then((cache) => cache.match(request));

  // Use the result of both the above Promises to return the Response. Promise.all returns an array, but we destructure that in the callback.
  return Promise.all([cachePromise, matchPromise])
    .then(([cache, cacheResponse]) => {
      // Kick off the update request
      const fetchPromise = fetch(request)
        .then((fetchResponse) => {
          // Cache the updated file and then return the response
          cache.put(request, fetchResponse.clone());
          return fetchResponse;
        });
      // return the cached response if we have it, otherwise the result of the fetch.
      return cacheResponse || fetchPromise;
    });
}

在这种情况下,我需要caches.open和cache.match(request)的结果为了执行背景提取和返回缓存的响应。我使用Promise.all和绘制结果数组保持代码整齐和描述性一起绘制他们。

命名这件事

在这些示例中,参数解构允许我们在Promise.all命名我们期望从解决的Promise传递给我们的结果。事实上,在任何地方我们使用参数解构,特别是数组,它允许我们早期和更具描述性地命名对象。这反过来使得代码更可读性和更长久的可维护性。

原文:https://philna.sh/blog/2017/02/09/toast-to-es2015-destructuring/?utm_source=javascriptweekly&utm_medium=email

上一篇 下一篇

猜你喜欢

热点阅读