JS 2020

- 4 mins

Javascript 的新特性都来自 TC39 finished-proposals ,发行时间是 2020,但是其中很多特性已经被发布到 browsers 的 nodeJS 或者 typescript 里面,可以试试。

Promise.allSettled()

Another Promise API is coming to the Promose Object family. The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

Promise.all(), Promise.race() 加之 Promise.allSettled() 越发强大和完善了。

用户场景:当需要集体展现多个异步执行的结果,并且直接给出行或不行的时候。

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

Dynamic Imports

A function allows you to lazily import a module at runtime. In another word, your import no longer needs to be static at the top of the file. You can load module asynchronously from anywhere in your code. This means you can delay the loading of non-essential dependencies in your application to improve performance.

现在可以通过这一新特性来优化依赖出现的时间。

// We are waiting the load of a module as a Promise
// when a user clicks a button
async function loadHugeLirary() {
  const lib = await import('someHugeLibrary')
}

// Lazy load on button click
btn.onclick = loadHugeLibrary

Optional Chainning

One of the most popular features maybe~ It's extremely useful when you working with an api or DB that returns a bunch of deeply nested objects, and you don't want your app break at runtime if intermediate properties on those objects are undefined.

语法一目了然,聪明且不会出错。

const user = {}

// No erros even though these props don't exist
user?.shopping?.list?.['baba']

Nullish Coalescing Operator ( ?? )

In many cases, you might want to set a default value for a property when it's undefined. This can already done in javascript using a Logical OR Operator but it can be problematic if the defined value is a zero or an empty string because javascript will coerce those values to false. It's super annoying because then you have to do runtime type checking in your code, in JS 2020 no more this. The double question mark is false only if it's null or undefined so the end result is more predictable code when setting default values.

又一个语法糖,语言的进化本身就对写语言的我们来说是个好事情。

const duration = 0

const animationTime = duration || 400
//runtime type checking to avoid errors caused by javascript automatically coerce.
const animationTime = (
  typeof duration  === 'number' && duration
) || 400
// with ?? is only false when it's null or undefined.
const animationTime = duration ?? 400

cosole.log(animationTime) 0

BigInt

New primitive data type BigInt represent numbers beyond javascript max safe integer value, which is limited to 64 bit, you can create a big int by adding an end to a regular integer or you can use bigint constructor to make numbers that are completely massive, but to be honest, it probably won't be needed by most developer unless you're doing an extremely precise time stamps or geometric calculations. It is a javascript primitive, so you should definately know about it.

新增了一个 data type,再面试的时候可以说 8 个 type 了。

const largestNum = BigInt(Number.Max_SAFE_INTEGER)

console.log(largestNum)

const utterlyMassiveInt = largestNum ** 23n

console.log(utterlyMassiveInt)

Worker Threads

The most exciting new feature in NodeJs has to be Worker Threads. One of the biggest limitations of Javascript that people like to point out is that it's single threaded that means you can't have more than one single processes running at the same time. But in 2020 that's no longer an issue becuase we now have worker threaded module and it opens door to use javascript in parallel.
// The worker_threads module enables the use of threads that excute javascript in parallel.
const worker = require('woker_threads')

ECMAScript Module

In Node13, you can import and export statements instead of require statements.

终于可以用了。

// const moment = reuqire('moment')

// Finally
import moment from 'moment'

References

https://www.youtube.com/watch?v=f0DrPLKf6Ro
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Yifan Chen

a junior developer for life

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin google pinterest medium wechat