当前位置:网站首页>【ECMAScript6】Promise
【ECMAScript6】Promise
2022-07-28 13:27:00 【Willard Leozi】
Promise Introduction and basic use
Promise yes ES6 The introduction of a new solution to asynchronous programming . Grammatically Promise It's a constructor , Used to encapsulate asynchronous operations and obtain the results of their success or failure .
const p = new Promise(function(resolve, reject) {
setTimeout(() => {
// let successData = ' User data in the database '
// resolve(successData)
let failData = ' Data read failed '
reject(failData)
}, 1000);
})
p.then(function(value) {
console.log('@success' + value)
}, function(error) {
console.error('@fail' + error)
})
Promise Encapsulate read file

// 1. introduce fs modular
const fs = require('fs')
// 2. Call method read file1 file
fs.readFile('./file1.md', (err, data) => {
// If it fails , Throws an error
if(err) throw err
// If there is no failure , Then output the file content
console.log(data.toString()) // I am a file11111
})
// 3. Use Promise encapsulation
const p = new Promise(function(resolve, reject){
fs.readFile('./file1.md1', (err, data) => {
// If it fails , Throws an error
if(err) reject(err)
// If there is no failure , Then output the file content
resolve(data)
})
})
p.then(function(value){
console.log(value.toString())
}, function(error){
console.error(error)
})
Promise encapsulation Ajax request
// Suppose the interface address is :https://api.apiopen.top/getJoke
// Native ajax request
// 1. Create objects
const xhr = new XMLHttpRequest()
// 2. initialization
xhr.open('GET', 'https://api.apiopen.top/getJoke')
// 3. send out
xhr.send()
// 4. The binding event , Process response results
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response)
}else {
console.error(xhr.status)
}
}
}
// adopt Promise After the encapsulation ajax request
const p = new Promise(function(resolve, rejece) {
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://api.apiopen.top/getJoke')
xhr.send()
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
}else {
rejects(xhr.status)
}
}
}
})
p.then(function(value) {
console.log(value)
}, function(error) {
console.error(error)
})
adopt Promise encapsulation ajax The benefits of : Data request and data processing understand coupling , There is no need to process data directly after data request , But through then Function to handle , Effectively solve callback hell .
Promise Object's then Method
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(' Request data successful ')
}, 1000)
})
// One Promise The instance object has three states , Initialization 、 Success and failure
const result = p.then(value => {
console.log(value)
}, error => {
console.log(error)
})
console.log(result) // Promise Instance object call then Method returns a Promise
Promise Instance object call then Methods after the Promise What determines the state of an object ?
This state is determined by the execution result of the callback function :
- If the return result in the callback function is Not Promise Type of type , The status is success , The return value is the successful value of the object
- If the return result in the callback function is Promise object , Then its status and return value are Promise In the same state
- If the Promise Status is success , Call then After that Promise The object status is success , And the value of success is also the same
- If the Promise The status is failure , Call then After that Promise The object status is failed , And the value of failure is also the same
- If the Promise Throw an error , Then its status is failed , And call then After that Promise The object status is also failed
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(' Request data successful ')
}, 1000)
})
const result = p.then(value => {
console.log(value)
// return 123
return new Promise((resolve, reject) => {
// resolve('ok')
// reject('error')
throw new Error(' error ')
})
}, error => {
console.log(error)
})
console.log(result)
// because then Characteristics of the method , therefore then Methods can be called chained , Chained calls can solve the problem of callback hell
p.then(value => {
}, error => {
}).then(value => {
}, error => {
})
Promise Application example : Read the contents of multiple files

- Recall the writing of hell
const fs = require('fs')
fs.readFile('./file1.md', (err, data1) => {
fs.readFile('./file2.md', (err, data2) => {
fs.readFile('./file3.md', (err, data3) => {
let result = data1 + '\r\n' + data2 + '\r\n' + data3
console.log(result)
})
})
})
- Promise Realization
const p = new Promise((resolve, reject) => {
fs.readFile('./file1.md', (err, data) => {
resolve(data)
})
})
p.then(value => {
return new Promise((resolve, reject) => {
fs.readFile('./file2.md', (err, data) => {
resolve([value, data])
})
})
}).then(value => {
return new Promise((resolve, reject) => {
fs.readFile('./file3.md', (err, data) => {
value.push(data)
resolve(value)
})
})
}).then(value => {
console.log(value.join('\r\n'))
})

Promise Object's catch Method
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(' Something went wrong ')
}, 1000)
})
p.catch(error => {
console.log(error)
})
adopt Promise On the object catch Method can directly capture error information , Not through then The second argument to the method
边栏推荐
- 夜神模拟器抓包微信小程序
- Shell基础概念和变量
- docker部署mysql 实现远程连接[通俗易懂]
- 二舅能治好年轻人的精神内耗吗?
- Led aquarium lamp touch chip-dlt8t02s-jericho
- Use and source code of livedata in jetpack family bucket
- Single option trading and cross trade
- 如何配置adb环境变量(环境变量在哪打开)
- Chinese translation of pointnet:deep learning on point sets for 3D classification and segmentation
- 无法连接服务器怎么办(原始服务器找不到目标资源)
猜你喜欢

Fast classification of array.group() in ES6

Have you seen the management area decoupling architecture? Can help customers solve big problems

基于神经网络的帧内预测和变换核选择

Leetcode daily question (2196. create binary tree from descriptions)

Have a part of the game, after NFT is disabled in my world

FFT海浪模拟

Parent and child of treeselect

FFT wave simulation

How much do you know about JVM memory management

IP电话系统和VoIP系统使用指南
随机推荐
FFT wave simulation
Extended operator
一根筋教育PHP培训 知行合一收热捧
docker部署mysql 实现远程连接[通俗易懂]
org.apache.ibatis.exceptions.TooManyResultsException的异常排查过程
[FPGA] FIR filter - half band filter
2021-10-06
GameStop熊市杀入NFT交易,老牌游戏零售商借Web3焕发第二春
Leetcdoe-342. Power of 4
Risk analysis of option trading
从手机厂高位“出走”的三个男人
Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)
leetcdoe-342. 4的幂
Realize the mutual value transfer between main window and sub window in WPF
Black cat takes you to learn EMMC Protocol Part 24: detailed explanation of EMMC bus test program (cmd19 & cmd14)
Using auto.js to realize the function of fifaol3 mobile terminal card interceptor
leetcode-136.只出现一次的数字
Fast classification of array.group() in ES6
Tidb 6.x in action was released, a summary of 6.x practices that condense the collective wisdom of the community!
【黑马早报】字节估值缩水,降至2700亿美元;“二舅”视频作者回应抄袭;任泽平称取消商品房预售制是大势所趋;美联储宣布再加息75个基点...