当前位置:网站首页>A case of using promise to read and write files in nodejs
A case of using promise to read and write files in nodejs
2022-07-19 00:16:00 【A dusty day】

31、 Use promise Implement the case of file reading before
In reference to util Module adoption : Follow common error first callback style functions ( Also is to (err, value) => ... Callback as the last parameter ), And return a return promise The object method of
And in chain splicing return The parameter that returns the parameter actually acts on the second chained formal parameter
Characteristics of chain call :
1、 first then The second one will be executed after execution then
2、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
31.1、 Basic Edition
// Basic Edition
const fs = require("fs");
const path = require("path");
let filePath1 = path.join(__dirname, "files", "1.txt");
let filePath2 = path.join(__dirname, "files", "2.txt");
let filePath3 = path.join(__dirname, "files", "3.txt");
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(filePath1,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1);
}
// What to do after reading
resolve(data1)
})
});
let p2 = 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(filePath2,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1);
}
// What to do after reading
resolve(data1)
})
});
let p3 = 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(filePath3,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1)
}
// What to do after reading
resolve(data1)
})
});
let str1 = "";
p1.then((data)=>{
str1+=data;
return p2
},(error1)=>{
console.log(" Read the file 1 Failure ", error1);
return error1
}).then((data)=>{
str1+=data;
return p3;
}).then((data)=>{
str1+=data;
console.log(str1);
});
32.2、 Encapsulated function version
const fs = require("fs");
const path = require("path");
let filePath1 = path.join(__dirname, "files", "1.txt");
let filePath2 = path.join(__dirname, "files", "2.txt");
let filePath3 = path.join(__dirname, "files", "3.txt");
function readFilePromise(filePath){
return new Promise((resolve, reject)=>{
fs.readFile(filePath,"utf-8",(error1, data1)=>{
if(error1){
// What you do when you fail
reject(error1);
}
// What to do after reading
resolve(data1)
})
});
}
let str1 = "";
readFilePromise(filePath1).then((data)=>{
str1+=data;
return readFilePromise(filePath2)
},(error1)=>{
console.log(" Read the file 1 Failure ", error1);
return error1
}).then((data)=>{
str1+=data;
return readFilePromise(filePath3);
}).then((data)=>{
str1+=data;
console.log(str1);
});33.3、util edition
node There is one of them. util Under tool module , There is one promisify Method , This method is equivalent to encapsulating a return promise Object function .
Document URL :util Utilities | Node.js API file
Pass in a function that follows the common error first callback style ( That is to (err, value) => ... Callback as the last parameter ), And return a return promise Version of .
let readFilePromise = util.promisify(fs.readFile); // This sentence of code is equivalent to the following code of the whole function
// function readFilePromise(filePath){
// return new Promise((resolve, reject)=>{
//
// fs.readFile(filePath,"utf-8",(error1, data1)=>{
// if(error1){
// // What you do when you fail
// reject(error1);
// }
// // What to do after reading
// resolve(data1)
// })
// });
// }
// summary :util.promisify(fs.readFile) Get one promise object Complete code :
const fs = require("fs");
const path = require("path");
const util = require("util");
let filePath1 = path.join(__dirname, "files", "1.txt");
let filePath2 = path.join(__dirname, "files", "2.txt");
let filePath3 = path.join(__dirname, "files", "3.txt");
let filePath4 = path.join(__dirname, "files", "data.txt");
let readFilePromise = util.promisify(fs.readFile);
let writeFilePromise = util.promisify(fs.writeFile);
let str1 = "";
readFilePromise(filePath1).then((data)=>{
str1+=data;
return readFilePromise(filePath2)
},(error1)=>{
console.log(" Read the file 1 Failure ", error1);
return error1
}).then((data)=>{
str1+=data;
return readFilePromise(filePath3);
}).then((data)=>{
str1+=data;
console.log(str1);
writeFilePromise(filePath4, str1);
});
边栏推荐
- ES6之箭头函数
- OpenCV DFT
- 软件测试面试(二)
- Openpose: real time multiplayer 2D pose estimation using partial affinity fields
- Kubesphere deployment
- API design principles from the requirements of compiler for instruction set
- 【JS】webAPI---第一弹
- boost. property_ The help class of tree parsing XML and the solution of Chinese parsing problem
- vertx编程需注意的点
- 【论文阅读】YOLOv7: Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors
猜你喜欢

HMS core graphics and image technology shows the latest functions and application scenarios, and accelerates the construction of digital intelligence life
![[JS] webapi --- the first bullet](/img/32/fba99c94e3b7f9eb38002335703e1b.png)
[JS] webapi --- the first bullet

笔记

About the use of go modules environment construction and package management tools

Fiddler cannot catch the package of wechat applet on PC

Delphi 485 Modbus RTU reading and writing RFID example source code

Mise en œuvre du modèle word2vec skip Gram

Word2Vec Skip-gram 模型實現

2022-07-15 advanced network engineering (XIX) BGP state machine, interaction principles between peers, factors affecting the establishment of peer relations, peer table, routing table, detailed routin

OpenCV DFT
随机推荐
从零开始配置 vim(4)——键盘映射的一些技巧
Visionmaster communicates MODBUS with youao robot ur5e
Glide source code analysis (4.13.2)
Interviewer: after working for two years, you can't solve such a simple algorithm problem?
Explanation of the taste of snow vegetables -- searching for Literature
软件测试面试(二)
P5js coffee cup steaming JS special effect
2022 latest Chinese Camtasia studio computer recording screen tool
2022-07-15 advanced network engineering (XIX) BGP state machine, interaction principles between peers, factors affecting the establishment of peer relations, peer table, routing table, detailed routin
Configuring VIM (4) from scratch -- some skills of keyboard mapping
【CANN训练营】基于昇腾CANN平台的AI CPU算子开发
Solution to the problem of heavy snow Vegetable Flavor -- p4017 maximum food chain count
CodeTON Round 1 (Div. 1 + Div. 2, Rated, Prizes)(A-C)
大雪菜味题解--P4017 最大食物链计数
WordPress主题分享:The7主题v10.11免费下载 2022年最新版
X Window
X Window
Redis distributed cache - redis master-slave
TCP 糊涂窗口综合症(silly window syndrome)与 rate-based 流控
2022-07-16 第五小组 修身课 学习笔记(every day)