New features of V8 v9.1: top-level await

V8 release v9.1 04 May 2021 release

V8 release v9.1

Chrome V8Released on May 4th v9.1, it brings several new features

1. Top-level await(Top level await)

Top-level await is enabled by default in V8 starting with v9.1 and is available without --harmony-top-level-await.

In one sentence: we can use it at the top level of the module awaitwithout adding additionalasync

so happy, this way you can avoid some redundant code

Try it...(please Chromeupgrade your browser to the latest version)

1. Write the following code in the page, write a sleepdelay function, and open the page
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
	const sleep = (time = 500) => {
      
      
		console.log('sleep 执行')
		return new Promise((resolve) => {
      
      
			setTimeout(() => {
      
      
				resolve(true)
			}, time)
		})
	}
	await sleep()
</script>

It actually reported an error. . .

top-level await

await is only valid in async functions and the top level bodies of modules

awaitValid only in top-level bodies of async functions and modules

so, let’s change it to , scriptand moduleopen the page again.

<script type="module">
	const sleep = (time = 500) => {
      
      
		console.log('sleep 执行')
		return new Promise((resolve) => {
      
      
			setTimeout(() => {
      
      
				resolve(true)
			}, time)
		})
	}
	await sleep()
</script>

success
execution succeed.

tips:

Top-level await only works at the top level of modules. There is no support for classic scripts or non-async functions.

Top awaitApplies only to the top level of the module. No support for classic scripts or non-async functions.

二、Private brand checks a.k.a. #foo in obj

The private brands check syntax is enabled by default in v9.1 without requiring --harmony-private-brand-checks. This feature extends the in operator to also work with private fields’ #-names.

inSimply put, the operator's check for private attributes is expanded.

1. Example
class A {
    
    
  static test(obj) {
    
    
    console.log(#foo in obj);
  }
  #foo = 0;
}
A.test(new A()); // true
A.test({
    
    }); // false
class B {
    
    
  #foo = 0;
}
A.test(new B()); // false; it's not the same #foo

3. Short built-in calls

reference

v8 v9.1

Guess you like

Origin blog.csdn.net/guoqiankunmiss/article/details/117651343
v8