当前位置:网站首页>nodeJS中使用promise实现文件读取、写入的案例
nodeJS中使用promise实现文件读取、写入的案例
2022-07-16 21:41:00 【小尘的一天】

31、使用promise实现之前文件读取的案例
在引用util模块采用:遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的对象方法
以及在链式拼接中return返回参数的参数实际上作用于了第二个链式的形参当中
链式调用的特点:
1、第一个then执行完会执行第二个then
2、then里面的函数的返回值,会被下一个then的形参接收
3、如果返回的是一个promise对象,下一个then的形参接收到的不是这个promise对象,而是这个promise对象内部调用resolve时候的实际参数
31.1、基础版
//基础版
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、同步代码
// console.log("同步代码");
// pending(进行中)、fulfilled(已成功)和rejected(已失败)
//2、异步代码
fs.readFile(filePath1,"utf-8",(error1, data1)=>{
if(error1){
//失败的时候做的事情
reject(error1);
}
//读取完之后做的事情
resolve(data1)
})
});
let p2 = new Promise((resolve, reject)=>{
//1、同步代码
// console.log("同步代码");
// pending(进行中)、fulfilled(已成功)和rejected(已失败)
//2、异步代码
fs.readFile(filePath2,"utf-8",(error1, data1)=>{
if(error1){
//失败的时候做的事情
reject(error1);
}
//读取完之后做的事情
resolve(data1)
})
});
let p3 = new Promise((resolve, reject)=>{
//1、同步代码
// console.log("同步代码");
// pending(进行中)、fulfilled(已成功)和rejected(已失败)
//2、异步代码
fs.readFile(filePath3,"utf-8",(error1, data1)=>{
if(error1){
//失败的时候做的事情
reject(error1)
}
//读取完之后做的事情
resolve(data1)
})
});
let str1 = "";
p1.then((data)=>{
str1+=data;
return p2
},(error1)=>{
console.log("读取文件1失败", error1);
return error1
}).then((data)=>{
str1+=data;
return p3;
}).then((data)=>{
str1+=data;
console.log(str1);
});
32.2、封装函数版
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){
//失败的时候做的事情
reject(error1);
}
//读取完之后做的事情
resolve(data1)
})
});
}
let str1 = "";
readFilePromise(filePath1).then((data)=>{
str1+=data;
return readFilePromise(filePath2)
},(error1)=>{
console.log("读取文件1失败", error1);
return error1
}).then((data)=>{
str1+=data;
return readFilePromise(filePath3);
}).then((data)=>{
str1+=data;
console.log(str1);
});33.3、util版本
node中有一个util工具模块下,有一个promisify方法,这个方法相当于封装了一个返回promise对象的函数。
文档网址:util 实用工具 | Node.js API 文档
传入一个遵循常见的错误优先的回调风格的函数(即以 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。
let readFilePromise = util.promisify(fs.readFile); //这一句代码相当于下面的整个函数的代码
// function readFilePromise(filePath){
// return new Promise((resolve, reject)=>{
//
// fs.readFile(filePath,"utf-8",(error1, data1)=>{
// if(error1){
// //失败的时候做的事情
// reject(error1);
// }
// //读取完之后做的事情
// resolve(data1)
// })
// });
// }
// 总结 :util.promisify(fs.readFile) 得到一个promise对象完整代码:
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("读取文件1失败", error1);
return error1
}).then((data)=>{
str1+=data;
return readFilePromise(filePath3);
}).then((data)=>{
str1+=data;
console.log(str1);
writeFilePromise(filePath4, str1);
});
边栏推荐
- Jvm-sandbox leads to the investigation of the target service JVM Metaspace oom
- pytest接口自动化测试框架 | @pytest.fixture()装饰器
- pytest接口自动化测试框架 | 对requests进行二次封装
- Use of res.cc
- Recent software test interview questions encountered by group Friends
- 吃鸡扔掉部分物资 绝地求生
- Solve the problem that WinDbg cannot load ntdll symbols
- 8、JVM优化简介
- Summary of this week 2
- [development tutorial 3] crazy shell arm function mobile phone - Introduction to the whole board resources
猜你喜欢

9、学会查看GC日志

Notes on scribbling questions in moher College -- SQL manual injection vulnerability test (mongodb database)

10.10:VectorDraw C# VS VectorDraw WEB/Crack-VectorDraw
![[arbre de décision] utilisation de l'arbre de décision pour le diagnostic du cancer du sein](/img/aa/ef3468f99d02845f3fd0414931073f.png)
[arbre de décision] utilisation de l'arbre de décision pour le diagnostic du cancer du sein

ACM板子
![Hibench generates benchmark data sets [wordcount as an example]](/img/c9/730cacfdfa677dcc8045edb4b1e02c.png)
Hibench generates benchmark data sets [wordcount as an example]

(pytorch advanced road 5) rnn/lstm/lstmp/gru

Pay attention to using yyyy-mm-dd in the code!

Send papers! AI, machine learning, CV boss scientific research project enrollment!

(pytorch advanced road III) conv2d
随机推荐
20220715 domestic CONDA does not FQ the method of installing the latest version of pytoch
Send papers! AI, machine learning, CV boss scientific research project enrollment!
二叉樹心得
pytest接口自动化测试框架 | pytest结合二次封装实现接口自动化
【Leetcode】225. Implement stack with queue
验证两个字符串一致
Yiwen teaches you how to design test cases
Clean the disk with CMD command (mainly the system disk)
中国碳陶复合材料市场调研与投资预测报告(2022版)
Verify that the two strings are consistent
Use of res.cc
嘘!摸鱼神器,别让老板知道!| 语音实时转文本,时序快速出预测,YOLOv6在就能用,一行命令整理CSV | ShowMeAI资讯日报
Compose 渐变色
Record of SQL questions of Niuke this week
5.< tag-动态规划和完全背包问题>lt.70. 爬楼梯 || 进阶版 + lt.322. 零钱兑换 + lt.139. 单词拆分 + lt.279.完全平方数 dbc
绝地求生 吃鸡 98k 不自动关镜子
OSPF comprehensive experiment
Programming examples of stm32f1 and stm32cubeide-w25q-spi-flash driver
SQL语句的执行计划
Offer gifts in July. Buy a cloud plate and give it to the super grade Guiqi. It's only limited to 2 months. If you want to buy it, hurry up