当前位置:网站首页>Introduction to promise module in nodejs
Introduction to promise module in nodejs
2022-07-19 00:26:00 【A dusty day】
1、Promise brief introduction
Promise Is a solution to asynchronous programming , More than traditional solutions —— Callback functions and events —— More reasonable and more powerful . It was first proposed and implemented by the community ,ES6 It's written into the language standard , Unify usage , Native provides Promise object .
So-called Promise, It's simply a container , It holds an event that will end in the future ( This is usually an asynchronous operation ) Result . grammatically ,Promise It's an object , From it you can get messages for asynchronous operations .Promise Provide uniform API, Various asynchronous operations can be handled in the same way .
Promise Objects have the following two characteristics .
(1) The state of the object is not affected by the outside world .Promise The object represents an asynchronous operation , There are three states :pending( Have in hand )、fulfilled( Have succeeded ) and rejected( Failed ). Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state . This is also Promise The origin of the name , It means the same thing in English “ promise ”, Says nothing else can be changed .
(2) Once the status changes , It won't change , You can get that at any time .Promise Object state changes , There are only two possibilities : from pending Turn into fulfilled And from the pending Turn into rejected. As long as those two things happen , The state is frozen , It won't change , It's going to stay that way , This is called resolved( Have to finalize the design ). If change has already happened , You again to Promise Object to add a callback function , And you'll get that immediately . With the event (Event) Completely different , The characteristic of the event is , If you missed it , To listen again , You don't get results .
30.2、Promise Basic use of
New Promise It's a container , It can store asynchronous operations , You can also store synchronous operations
const fs = require("fs");
const path = require("path");
let filePath = path.join(__dirname, "files", "3.txt");
// Asynchronous operations may succeed or fail
// First parameter resolve , Function executed when successful
// The second parameter reject , The function executed when it fails
let p1 = new Promise((resolve, reject)=>{
//1、 Synchronization code
console.log(" Synchronization code ");
// pending( Have in hand )、fulfilled( Have succeeded ) and rejected( Failed )
//2、 Asynchronous code
fs.readFile(filePath,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1); // Call back p1.then The second function of
}
// What to do after reading
resolve(data1); // Call back p1.then The second function of
})
});
p1.then((data1)=>{
console.log(" Read successful ", data1);
},(error1)=>{
console.log(" Read failed ", error1);
});30.3、Promise Of then Characteristics of chain call
Characteristics of chain call :1、 first then The second one will be executed after execution then2、then The return value of the function inside , Will be next then The formal parameters of are received 3、 If you return a promise object , next then The formal parameter of received is not this promise object , It's this promise Call... Inside the object resolve Actual parameters at time
const fs = require("fs");
const path = require("path");
let filePath = path.join(__dirname, "files", "3.txt");
// New Promise It's a container , It can store asynchronous operations , You can also store synchronous operations
// Asynchronous operations may succeed or fail
// First parameter resolve , Function executed when successful
// The second parameter reject , The function executed when it fails
let p1 = new Promise((resolve, reject)=>{
//1、 Synchronization code
// console.log(" Synchronization code ");
// pending( Have in hand )、fulfilled( Have succeeded ) and rejected( Failed )
//2、 Asynchronous code
fs.readFile(filePath,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1)
}
// What to do after reading
resolve("resolve The parameter of ")
})
});
// The industry puts promise then The way of writing is called driving a train
p1.then((data1)=>{
return p1
},(error1)=>{
console.log(" Read failed ", error1);
return error1
}).then((data)=>{
console.log(data); // “resolve("resolve The parameter of ")
});边栏推荐
- 微信小程序开发学习2(模板与配置)
- Electron如何打包使其支持龙芯和方腾、兆芯平台的麒麟系统
- Umap introduction and code examples
- 笔记
- Bufferbloat and inflation
- Use protobuf in the program
- What are the advantages of using gtid to configure replication relative to coordinate position
- 没有老板的乐视员工过上“神仙日子”,靠什么?
- QT工具——moc、rcc、uic
- [JS] webapi --- the first bullet
猜你喜欢

Word2Vec Skip-gram 模型实现

没有老板的乐视员工过上“神仙日子”,靠什么?
![[acwing weekly rematch] game 60 20220716](/img/59/38fde90ff1d4221bd35379df1291d1.png)
[acwing weekly rematch] game 60 20220716

2022-07-15 网工进阶(十九)BGP-状态机、对等体之间的交互原则、影响对等体关系建立的因素、对等体表、路由表、详细路由表、路由属性

QT tools - MOC, RCC, UIC

Wechat applet development learning 2 (template and configuration)

vertx编程需注意的点

CodeTON Round 1 (Div. 1 + Div. 2, Rated, Prizes)(A-C)

What do LETV employees rely on to live a "fairy life" without a boss?

Daily question 1: merge two sorted linked lists (Sword finger offer25)
随机推荐
外部PLC触发VisionMaster多流程运行PLC部分特殊说明
This host supports Intel VT-x, but Intel VT-x is disabled
Vs publish websites using webdeploy
QT工具——moc、rcc、uic
ans1编码解析
Electron如何打包使其支持龙芯和方腾、兆芯平台的麒麟系统
【论文阅读】YOLOv7: Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors
Customized serialization protocol, which is flexible, but not universal
原子类及CAS
Wechat applet Development Learning 3 (wxss Template and Global configuration)
Cookie和Session、JWT的区别
Using backup to restore the database, but there is no control file. How to solve the file
eTS开发方式三方组件推荐【系列1】
Mysql的redolog和binlog
例行运维巡检,通过监控视图发现客户
Delphi 485 Modbus RTU reading and writing RFID example source code
Shell's third day small exercise: access the self built nextcloud network disk service through the self built DNS server
2022 latest Chinese Camtasia studio computer recording screen tool
有效降低项目成本,从项目采购管理抓起
2022 - 07 - 16 notes d'étude pour le cours d'auto - culture du groupe 5 (tous les jours)