当前位置:网站首页>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 
边栏推荐
- The programmer's girlfriend gave me a fatigue driving test
- Matlab saves triangulation results as STL files
- Error when starting PHP: [pool www] cannot get uid for user '@php_ fpm_ [email protected]’
- Design e-commerce seckill system
- One revolution, two forces and three links: the "carbon reduction" road map behind the industrial energy efficiency improvement action plan
- Pycharm useful shortcut keys
- 2022-2028 global elevator emergency communication system industry research and trend analysis report
- Software engineering best practices - project requirements analysis
- BeanUtils. Copyproperties() vs. mapstruct
- 让企业数字化砸锅和IT主管背锅的软件供应链安全风险指北
猜你喜欢

ABAQUS 2022 software installation package and installation tutorial

76页智慧物流园区综合解决方案2022(附下载)

1. crawler's beautifulsoup parsing library & online parsing image verification code

Redis - how to understand publishing and subscribing

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

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

Why should VR panoramic shooting join us? Leverage resources to achieve win-win results

2022-2028 global herbal diet tea industry research and trend analysis report

女朋友说:你要搞懂了MySQL三大日志,我就让你嘿嘿嘿!

How to edit special effects in VR panorama? How to display detailed functions?
随机推荐
Dataloader source code_ DataLoader
MaxPool2d详解--在数组和图像中的应用
leetcode 474. Ones and Zeroes 一和零(中等)
6-1 exploit -ftp exploit
Is it safe to choose mobile phone for stock trading account opening in Hangzhou?
Repetition is the mother of skill
什么是SRM系统,如何规范公司内部采购流程
让企业数字化砸锅和IT主管背锅的软件供应链安全风险指北
Reason why wechat payment wxpaypubhelper V3 callback XML is empty
Advanced mathematical modeling
shell 同时执行多任务下载视频
Shell multitasking to download video at the same time
How to distinguish between platform security and online hype? What are the stop loss techniques for online speculation?
Five minutes to understand the exploratory test
Solutions to errors in installing OpenSSL for CentOS 6.3 x64 PHP 5.2.6 extensions
Techo youth 2022 academic year college open class: behind the live broadcast of Lianmai, explore how to apply audio and video technology
C /platform:anycpu32bitpererrored can only be used with /t:exe, /t:winexe and /t:appcontainerexe
1175. 质数排列 / 剑指 Offer II 104. 排列的数目
ABAQUS 2022 software installation package and installation tutorial
Dell r720 server installation network card Broadcom 5720 driver