当前位置:网站首页>Introduction to ES6 promise, new features of ES7 and es8 async and await
Introduction to ES6 promise, new features of ES7 and es8 async and await
2022-07-01 00:16:00 【1900's 88 keys】
ES6-Promise
Promise brief introduction
Promise yes ES6 Introduce a new solution to asynchronous programming . Grammatically
PromiseIt's a constructor , Used to encapsulate asynchronous operations and obtain the results of their success or failure
adoptnewKeywords can be instantiated into aPromiseObject usage :
new Promise(excutor){}
Parameters :excutorIs a function like thisfunction(resolve, reject){}
resolve:resolveThe method can changePromise Instance objectThe status of is successreject:reject: The method can changepromise Instance objectThe status of is Failure
// Instantiation Promise object
const p = new Promise(function(resolve, reject){
// Encapsulating asynchronous operations
})
Promise.prototype.then Method
usage :
p.then(function(value){}, function(){}}
promiseobjectthenMethod has two functions as formal parameters- When
promiseObject state is success The first function is called when , The first function also has a formal parametervaluevalueIs the value of the asynchronous call byresolve MethodReturned data- When
promiseObject state is Failure Call the second function , The second function also has a formal parameterreasonreasonThe value of is an asynchronous call byreject MethodError returned
Successful asynchronous read :
// call promise Object's then Method
p.then(function(value){
console.log(value); // User data
},function(reason){
})
Failed asynchronous reads :
// Instantiation Promise object
const p = new Promise(function(resolve, reject){
// Encapsulating asynchronous operations
setTimeout(function(){
let err = " Read failed ";
reject(err)
})
})
// call promise Object's then Method
p.then(function(value){
},function(reason){
console.error(reason); // Read failed
})
then Method returns the result
then Method returns the result Also a Promise object , The state of the object is determined by the execution result of the callback function
- If the result returned in the callback function is non Promise Properties of type , Status is success , The return value is the successful value of the object
// Instantiation Promise object
const p = new Promise(function (resolve, reject) {
// Encapsulating asynchronous operations
setTimeout(function () {
let data = " User data "
resolve(data)
})
})
// call promise Object's then Method
const result = p.then(function (value) {
console.log(value);
// 1. Return non Promise Properties of type , Return successful Promise Type object
// return "iloveyou"
// 2. return Promise object
return new Promise((resolve, reject)=>{
// 2.1 success Return successful Promise Type object
resolve(" success !")
// // 2.2 Failure Return failed Promise Type object
// reject(" Failure !")
})
// 3. Throw an error Return failed Promise Type object
// throw new Error(" Error ")
}, function (reason) {
})
console.log(result);

Promise.prototype.catch Method
catch MethodCan get Promise The status of type object is failed value
- This method is equivalent to
thenMethod parameters do not write the contents of the first callback function
usage :p.catch(function(reason){})
// Instantiation Promise object
const p = new Promise(function (resolve, reject) {
// Encapsulating asynchronous operations
setTimeout(function () {
// Set up p The state of the object is failed , And set the failed value
let err = " Read failed ";
reject(err)
})
})
p.catch(function(reason){
console.warn(reason);
})

ES7 New characteristics
Array.prototype.includes
includesMethod is used to detect whether an array contains an element , Returns a Boolean value
const arr = [" The river "," Heart ape "," Wooden Dragon "," Dao gui "," Yima "];
console.log(arr.includes(" Heart ape "));// true
console.log(arr.includes(" Spider essence "));// false
Exponential operators
stay ES7 Index operator is introduced in
**, Used to implement power operation , Function andMath.pow()The result is the same
console.log(5 ** 2);//25
console.log(2 ** 10);//1024
ES8 New characteristics -async and await
async and await
ES8 Proposed async and await Keyword the combination of two syntaxes can make asynchronous code look like synchronous code , Can solve
promise objectContinuous usethenMethod code is not concise
async function
async functionThe return value of is Promise Type object- Promise The result of the type object is determined by
async functionThe return value of the execution determines
- If the result returned is not a Promise Object of type , The result returned is the status success Of
Promise object- If the result returned is Promise Object of type , The result returned
Promise objectThe status is returned by the Promise The state of an object of type determines , If it works , The returned result status is also success , If it fails, the returned result status is also failed , The value of the returned result is also Promise The value of an object of type determines
async function fn() {
// 1. Return non Promise Properties of type , Return successful Promise Type object
// return "iloveyou"
// 2. Throw an error Return failed Promise Type object
// throw new Error(" Error ")
// 3. return Promise object
return new Promise((resolve, reject) => {
// 3.1 success Return successful Promise Type object
resolve(" success !")
// // 3.2 Failure Return failed Promise Type object
// reject(" Failure !")
})
}
const result = fn();
console.log(result);

await expression
awaitKeywords must be written in async FunctionawaitThe expression on the right side of the keyword is generally promise objectawaitThe return is promise The value of successawaitThe expression returns promise The value of successawaitOf expression promise Status failed , Will throw an exception , Need to pass throughtry...catchCapture processing
await When the expression state is successful
// await Put it on async Function
async function main() {
let result = await new Promise((resolve, reject) => {
resolve(" User data ");
})
// Print await The expression returns the value
console.log(result);
}
// Call function
main()// User data
await When the expression state fails , adopt try...catch Capture processing
// await Put it on async Function
async function main() {
try {
let result = await new Promise((resolve, reject) => {
reject(" Read failed ")
})
// Print await The expression returns the value
console.log(result);
}
catch (e) {
console.warn(e);
}
}
// Call function
main()

async and await Combined read file
File path 
JS Code
// introduce fs File module
const fs = require("fs");
// Read 《 Climbing crane and bird tower 》
function readPoetry(){
return new Promise((resolve, reject)=>{
fs.readFile("./resource/ Climb the stork tower .md", (err, data)=>{
if(err){
reject(err)
}else{
resolve(data)
}
})
})
}
// Read translation
function readTranslation(){
return new Promise((resolve, reject)=>{
fs.readFile("./resource/ translation .md", (err, data)=>{
if(err){
reject(err)
}else{
resolve(data)
}
})
})
}
// Read authoring background
function readBackground(){
return new Promise((resolve, reject)=>{
fs.readFile("./resource/ Background .md", (err, data)=>{
if(err){
reject(err)
}else{
resolve(data)
}
})
})
}
// Make a statement async function
async function main(){
// obtain 《 Climbing crane and bird tower 》 Content
let poetry = await readPoetry();
// obtain The content of the translation is
let translation = await readTranslation();
// obtain Creation background content
let background = await readBackground();
console.log(poetry.toString());
console.log(translation.toString());
console.log(background.toString());
}
// perform main function
main()
Execution results 
async and await Combined transmission AJAX request
Code
<script>
// send out AJAX request , Return is Promise object
function sendAJAX(url) {
return new Promise((reslove, reject) => {
// 1. establish AJAX object
const xhr = new XMLHttpRequest();
// 2. initialization
xhr.open("GET", url);
// 3. send out
xhr.send();
// 4. Event binding
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// success
reslove(xhr.response);
}else{
// Failure
reject(xhr.status)
}
}
}
})
}
// test
async function main(){
// send out AJAX request
let data = await sendAJAX("https://api.apiopen.top/getJoke");
console.log(data);
}
main()
</script>
effect 
边栏推荐
- 2022-2028 global 3D printing ASA consumables industry research and trend analysis report
- ABAQUS 2022 software installation package and installation tutorial
- What is SRM system and how to standardize the internal procurement process of the company
- 深入理解 Jetpack Compose 内核:SlotTable 系统
- To tell you the truth, ThreadLocal is really not an advanced thing
- Shell multitasking to download video at the same time
- 2022-2028 global retro glass industry research and trend analysis report
- Fh6908a negative pole turn off synchronous rectification analog low voltage drop diode control IC chip tsot23-6 ultra low power rectifier 1W power consumption < 100ua static replacement mp6908
- leetcode 474. Ones and zeroes (medium)
- Never use redis expired monitoring to implement scheduled tasks!
猜你喜欢

The college entrance examination in 2022 is over. Does anyone really think programmers don't need to study after work?

One revolution, two forces and three links: the "carbon reduction" road map behind the industrial energy efficiency improvement action plan

Which is better, server rental or hosting services in the United States?

2022-2028 global rampant travel industry research and trend analysis report

5G智慧建筑解决方案2021

Manage edge browser settings (ie mode, homepage binding, etc.) through group policy in the enterprise

VR panorama adds contrast function to make the display of differentiation effect more intuitive!

In depth understanding of jetpack compose kernel: slottable system

深入理解 Jetpack Compose 内核:SlotTable 系统

Software engineering best practices - project requirements analysis
随机推荐
Makefile notes (Yiwen Institute makefile)
需求评审,测试人员应该发挥怎样的价值?两分钟让你不再懵逼
shell 同时执行多任务下载视频
Lombok
Bridge emqx cloud data to AWS IOT through the public network
Kubernetes ---- pod configuration container start command
To tell you the truth, ThreadLocal is really not an advanced thing
1. crawler's beautifulsoup parsing library & online parsing image verification code
File reading and writing for rust file system processing - rust Practice Guide
Detailed explanation of conv2d -- use in arrays and images
In depth understanding of jetpack compose kernel: slottable system
Is it safe to choose mobile phone for stock trading account opening in Hangzhou?
BeanUtils. Copyproperties() vs. mapstruct
LVM snapshot: backup based on LVM snapshot
conv2d详解--在数组和图像中的使用
Software supply chain security risk pointing North for enterprise digitalization and it executives
lvm-snapshot:基于LVM快照的备份
How to distinguish between platform security and online hype? What are the stop loss techniques for online speculation?
Is it safe to buy funds on the compass?
Manage edge browser settings (ie mode, homepage binding, etc.) through group policy in the enterprise