当前位置:网站首页>Simply understand the promise of ES6
Simply understand the promise of ES6
2022-07-06 13:50:00 【Ling Xiaoding】
Simple understanding ES6 Of Promise
List of articles
Preface
PromiseIs a solution to asynchronous programming : Grammatically speaking ,promiseIt's an object , From it you can get messages for asynchronous operations ; From the original point of view , It's a promise , Promise that it will give you a result after a period of timePromiseIt can ensure that asynchronous requests become executed sequentiallyConcept :
PromiseyesES6New grammar in , Itself a constructor ; EverynewComing outPromiseInstance object , Both represent an asynchronous operationeffect : Solved the problem of callback hell ( That is, asynchronous nested calls )
Back to hell : Refers to the callback function , The code form of nested callback function ; If the nesting level is very deep , It's hell ;
Callback hell is not conducive to code reading 、 Maintenance and later expansion
Promise How to use it?
- Create specific asynchronous operation objects
const p = new Promise(function(successCb, errorCb){
// In this function Define specific asynchronous operations in
// successCb Successful callback
// errorCb Failed callback
})
PromiseIt's a constructor , SurenewAn object , Itself is an asynchronous operationPromiseOfthenMethodPromiseThere are two method parameters when usingsuccessCb,errorCbRespectively represents the success or failure of executionPromiseObjects can pass throughthenMethod pairsuccessCbanderrorCbTo call
There are two specific situations as follows :
result.then(function(data){
/* Successful callback */},function(data){
/* Failed callback */})
result.then(function(){
/* Successful callback */}).catch(function(data){
/* Failed callback */})
In the former then Method accepts successCb and errorCb Callback function
The latter passes then and catch The two methods accept successCb and errorCb Callback function
- example :
// introduce fs modular
const fs = require('fs')
// 4) Promise Intervene and enrich the operation ( Join the success 、 Failed callback )
function getFileCont(filename) {
// Instantiation Promise object , Used to indicate asynchronous operation
// new Promise(function(successCb function , errorCb function ){})
// successCb: The current asynchronous operation is ok In this case, the execution is triggered resolve
// errorCb: An error occurred in the current asynchronous operation ( exceeding one's expectations ) Next trigger execution reject
return new Promise(function(successCb, errorCb) {
// Embody asynchronous process
fs.readFile(filename, 'utf8', function(err, data) {
if (err) {
return errorCb(' An error occurred while reading the file :' + err)
}
// All operations are ok Normal handling in case , Give the processed results to resolve call ( return )
successCb(data)
})
})
}
// The following can guarantee In order Get the results
getFileCont('./files/1.txt').then(function(result) {
console.log(result)
return getFileCont('./files/2.txt')
}).then(function(result){
console.log(result)
return getFileCont('./files/3.txt')
}).then(function(result){
console.log(result)
}).catch(function(err){
console.log(err)
})
ES7 Of async and await
ES7MediumasyncandawaitCan be simplifiedPromisecall , ImprovePromiseCode reading and understandingasyncandawaitCombine , It can make the asynchronous call not returnPromise, And just putthenParameters of parameter method ( It's alsosuccessCbfunction arguments ) Come back , Make code more frugal , Improve code development efficiency , It can also ensure the sequential execution of asynchronous callsasync、awaitVarious use cases :
Be careful :
asyncandawaitMust appear at the same time
OneasyncCan correspond to multipleawaitawaitThe result of modification must bePromiseobject
var obj = {
async getInfo(){
await getXXXX()
await getXXXX()
}
}
or
function ffff(){
// async It needs to be set to Promise The nearest outer layer of the object function In front of
getInfo(async function(){
await getXXXX()
//console.log(getXXXX())
})
}
or
async function XXXX(){
await getXXXX()
}
summary
new Promise()Instantiate objects , The parameter callback function will have two callbackssuccessCbanderrorCbParameters- These two callbacks can be through
thenandcatch()Receive , But the asynchronous calling code is more or less reflected in the degree of hell callback asyncandawaitcombination , The return ofPromiseDirectly intosuccessCbArguments of , Greatly simplifies the complexity of code development , Improve development efficiency- If necessary , adopt
try/catchcaptureasyncandawait - Usually use ,
async、await、abnormalThe solution of asynchronous sequential execution provided by the combination of three technologies
async function getThreeFile(){
try{
console.log(await getFileCont('./files/1.txt'))
console.log(await getFileCont('./files/2.txt'))
console.log(await getFileCont('./files/3.txt'))
}catch(err){
console.log(err)
}
}
getThreeFile()
边栏推荐
- 2022 Teddy cup data mining challenge question C idea and post game summary
- 2.初识C语言(2)
- FAQs and answers to the imitation Niuke technology blog project (III)
- [the Nine Yang Manual] 2016 Fudan University Applied Statistics real problem + analysis
- 【黑马早报】上海市监局回应钟薛高烧不化;麦趣尔承认两批次纯牛奶不合格;微信内测一个手机可注册俩号;度小满回应存款变理财产品...
- 扑克牌游戏程序——人机对抗
- 2. Preliminary exercises of C language (2)
- The latest tank battle 2022 full development notes-1
- The latest tank battle 2022 - Notes on the whole development -2
- 9. Pointer (upper)
猜你喜欢

【手撕代码】单例模式及生产者/消费者模式

魏牌:产品叫好声一片,但为何销量还是受挫

Using spacedesk to realize any device in the LAN as a computer expansion screen

C语言入门指南

The latest tank battle 2022 full development notes-1

Write a program to simulate the traffic lights in real life.

Read only error handling

撲克牌遊戲程序——人機對抗

仿牛客技术博客项目常见问题及解答(一)

canvas基础1 - 画直线(通俗易懂)
随机推荐
Detailed explanation of redis' distributed lock principle
FAQs and answers to the imitation Niuke technology blog project (I)
实验六 继承和多态
Safe driving skills on ice and snow roads
The difference between cookies and sessions
自定义RPC项目——常见问题及详解(注册中心)
5. Download and use of MSDN
[modern Chinese history] Chapter V test
3.输入和输出函数(printf、scanf、getchar和putchar)
实验七 常用类的使用(修正帖)
js判断对象是否是数组的几种方式
1. Preliminary exercises of C language (1)
受检异常和非受检异常的区别和理解
Beautified table style
C language Getting Started Guide
[the Nine Yang Manual] 2020 Fudan University Applied Statistics real problem + analysis
[中国近代史] 第九章测验
7-5 走楼梯升级版(PTA程序设计)
3. C language uses algebraic cofactor to calculate determinant
4. Binary search