当前位置:网站首页>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 
边栏推荐
- DNS server setup, forwarding, master-slave configuration
- C /platform:anycpu32bitpererrored can only be used with /t:exe, /t:winexe and /t:appcontainerexe
- 206页上海BIM技术应用与发展报告2021
- Ditto set global paste only text shortcuts
- Prospects of world digitalization and machine intelligence in the next decade
- 2022-2028 global single travel industry research and trend analysis report
- In depth understanding of jetpack compose kernel: slottable system
- What value should testers play in requirements review? Two minutes will stop you from being stupid
- 2022-2028 global 3D printing ASA consumables industry research and trend analysis report
- Five minutes to understand the exploratory test
猜你喜欢

2022-2028 global public address fire alarm system industry research and trend analysis report

MaxPool2d详解--在数组和图像中的应用

ABAQUS 2022 latest edition - perfect realistic simulation solution

2022-2028 global ultra high purity electrolytic iron sheet industry research and trend analysis report

Software supply chain security risk pointing North for enterprise digitalization and it executives

Redis - sentinel mode

2022-2028 global ethylene oxide scrubber industry research and trend analysis report

Bridge emqx cloud data to AWS IOT through the public network

The programmer's girlfriend gave me a fatigue driving test

The full technology stack, full scene and full role cloud native series training was launched to help enterprises build a hard core cloud native technology team
随机推荐
Is it safe to buy funds on the compass?
LVM snapshot: preparation of backup based on LVM snapshot
Wordpress blog uses volcano engine veimagex for static resource CDN acceleration (free)
Prospects of world digitalization and machine intelligence in the next decade
Flitter - sort list sort
C# /platform:anycpu32bitpreferred 只能与 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用
VR panorama adds contrast function to make the display of differentiation effect more intuitive!
Why did kubernetes win? The changes in the container circle!
MaxPool2d详解--在数组和图像中的应用
One revolution, two forces and three links: the "carbon reduction" road map behind the industrial energy efficiency improvement action plan
Redis - cache penetration, cache breakdown, cache avalanche
The difference between union and union all in MySQL
Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)
Development of wireless U-shaped ultrasonic electric toothbrush
Using Excel to quickly generate SQL statements
Implementation of OSD on Hisilicon platform (1)
2022-2028 global ethylene oxide scrubber industry research and trend analysis report
2022-2028 global single travel industry research and trend analysis report
如何关闭一个开放的DNS解析器
ABAQUS 2022 software installation package and installation tutorial