当前位置:网站首页>A simple output method of promise object to the result in nodejs (it is recommended to use the asynchronous ultimate scheme async+await)
A simple output method of promise object to the result in nodejs (it is recommended to use the asynchronous ultimate scheme async+await)
2022-07-19 11:07:00 【A dusty day】
One 、promise Object utilization all() Method to achieve concise output
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); // This sentence of code is equivalent to the following code of the whole function
let writeFilePromise = util.promisify(fs.writeFile);
Promise.all([readFilePromise(filePath1,"utf-8"), readFilePromise(filePath2,"utf-8"),readFilePromise(filePath3,"utf-8")]).then((data)=>{
let str1 = data.join("");
writeFilePromise(filePath4,str1);
}).catch((error)=>{
// Just execute p1,p2 One of them reported an error , Will execute the code here
console.log(error);
});1.1、async+await edition ()
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.xt");
let readFile = util.promisify(fs.readFile);
let writeFile = util.promisify(fs.writeFile);
async function func() {
let data1 = await readFile(filePath1, "utf-8");
let data2 = await readFile(filePath2, "utf-8");
let data3 = await readFile(filePath3, "utf-8");
console.log(data1+data2+data3);
writeFile(filePath4, data1+data2+data3)
}
func();async+await edition () There is a convenience handler for the output results , utilize await Keywords make promise Object to get the resolve Parameter is assigned to a variable , Let's splice variables , You can achieve the effect of splicing .
Two 、Promise Other common methods ( Aim at then() Chain method )
2.1、promise object catch() Methods and finally() Method , stay then() Method chain splicing to achieve error output .
as well as finally() Method promises to execute the code here in case of success or failure
// commonly , We will put the following code :
p1.then((data1)=>{
console.log(" Promise success ", data1);
},(error1)=>{
console.log(" Promises fail ", error1);
});
// It's written in
p1.then((data1)=>{
console.log(" Promise success ", data1);
}).catch((error1)=>{
console.log(" Promises fail ", error1);
}).finally(()=>{
console.log(" Promise that success and failure will execute the code here ");
});
2.2、Promise Class all() Method to achieve concise output
Parameters : Is an array , Array elements are Promise Instance object , Only all in the array Promise succeed , Will execute then The first callback
Grammatical structure :
Is to store the values in the array into a variable , Using the splicing of arrays, the results are output
Promise.all([p1,p2]).then((data)=>{}
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 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)
})
});
Promise.all([p1,p2]).then((data)=>{
// data Is an array , Namely p1 and p2 Last data
console.log(data); // [ ' I ', ' Love ' ]
console.log(data.join("")); // I love
}).catch((error)=>{
// Just execute p1,p2 One of them reported an error , Will execute the code here
console.log(error);
});2.3、Promise Class race() Method
Parameters : Is an array , Array elements are Promise Instance object , Just any one in the array Promise succeed , Will execute then The first callback , And only execute 1 Time .
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 readFilePromise = util.promisify(fs.readFile);
let p1 = readFilePromise(filePath1,"utf-8")
let p2 = readFilePromise(filePath2,"utf-8")
Promise.race([p1,p2]).then((data)=>{
// p1,p2 As long as one of them is finished , Will execute the code here again , And the code here will only execute 1 Time
console.log(123);
console.log(data);
});
//123
// I 33、 Asynchronous ultimate solution async+await
33.1、async+await The basic structure
We have written similar code before :
function func(a, b) {
return a + b
}
let ret = func(10, 30);
let ret1 = func(50, 320);
let ret2 = func(1560, 30);
let ret3 = func(10, 3560);
console.log(ret + ret1 + ret2 + ret3);If Promise Objects can also have corresponding ways to receive , Write similar :
let data1 = await readfilePromise; // Get the successful data directly
async The final format of is as follows :
async function func() {
let data1 = await promise object 1;
let data2 = await promise object 2;
let data3 = await promise object 3;
}
// It's equivalent to making asynchronous function objects 1 After execution , Then execute the asynchronous function object 2, Then execute the asynchronous function object 3Case to see 2.5
3.2、 matters needing attention
If await Only one basic data type is written later , Wrap this basic data type , Pack it as a Promise object
async function func() {
let data1 = await 123;
//1. await Only one basic data type is written later Wrap this basic data type , Pack it as a Promise object
// namely data1 amount to : new Promise((resolve,reject)=>{resolve(123)})
console.log("data1:", data1); //data1: 123
return data1
// return await data1
}
let a = func();
a.then((data)=>{
console.log(data); //123 Received the above return value Promise Object execution results
});If await There's a Promise, Will be able to resolve The value of the return
async Inside the function await It's asynchronous , Not synchronization
async function func() {
console.log("start-------");
let data1 = await readFile(filePath1, "utf-8");
console.log("end-----------");
let data2 = await readFile(filePath2, "utf-8");
let data3 = await readFile(filePath3, "utf-8");
console.log(data1+data2+data3);
}
console.log("start");
func();
console.log("end");
// The output results are as follows :
//start
//start-------
//end
//end-----------Error handling ( external Handle )
async function func() {
let data1 = await readFile(filePath1, "utf-8");
let data2 = await readFile(filePath2, "utf-8");
let data3 = await readFile(filePath3, "utf-8");
console.log(data1+data2+data3);
// writeFile(filePath4, data1+data2+data3)
}
func().catch( error => {
console.log(error);
} ).finally(()=>{
console.log("finally");
});Error handling ( Internal processing )
async function func() {
try{
let data1 = await readFile(filePath1, "utf-8");
let data2 = await readFile(filePath2, "utf-8");
let data3 = await readFile(filePath3, "utf-8");
}
catch (error) {
console.log(error);
return
}
finally {
console.log("finally");
}
console.log("end");
}
func();边栏推荐
- Nombre d'entrées nombre d'entrées numériques pures limite de longueur maximale
- Develop the first Flink app
- 【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码
- PPDE第二季度迎新 | 欢迎22位AI开发者加入飞桨开发者技术专家计划!
- [Huawei cloud IOT] reading notes, "Internet of things: core technology and security of the Internet of things", Chapter 3 (2)
- OpenCV编程:OpenCV3.X训练自己的分类器
- Pytoch framework learning record 1 cifar-10 classification
- 【CSP-J 2021】总结
- Maximal semi connected subgraph (tarjan contraction + topological ordering + DP longest chain)
- Establishment of redis cluster, one master, two slave and three Sentinels
猜你喜欢

LeetCode 2319. Judge whether the matrix is an X matrix

Unity3d 读取mpu9250 例子原代码

How to build dashboard and knowledge base in double chain note taking software? Take the embedded widget library notionpet as an example

腾讯云服务器利用镜像部署WordPress个人网站!

leetcode-08

Environment variable configuration of win10

Pytoch learning record 2 linear regression (tensor, variable)

Pytorch与权重衰减(L2范数)
![[leetcode weekly replay] 302 weekly 20220717](/img/38/446db9b4755f8b30f9887faede7e95.png)
[leetcode weekly replay] 302 weekly 20220717

LeetCode 2335. Minimum total time required to fill the cup
随机推荐
Antd drop-down multiple options to transfer values to the background for query operations
Paper notes: mind the gap an empirical evaluation of impaction ofmissing values techniques in timeseries
How can enterprise telecommuting be more efficient?
Unity3d 读取mpu9250 例子原代码
Integrated network architecture and network slicing technology of air, earth and sea
数据库锁的介绍与InnoDB共享,排他锁
Introduction to sap appgyver
nodeJS中promise对象对结果简便输出办法(建议使用异步终极方案 async+await)
To get to the bottom: Principle Analysis of Objective-C correlation attribute
ROS 重名
关于hping打流测试工具
antd 下拉多选传值到后台做查询操作
Google Earth engine - Hansen global forest change v1.8 (2000-2020) forest coverage and forest loss data set
UE4 understanding of animation blueprint
6G中的卫星通信高效天基计算技术
Unity Dropdown(可编辑,可输入)下拉选择框,带文本联想
MySQL query error
ENVI_ Idl: use the inverse distance weight method to select the nearest n points for interpolation (bottom implementation) and output them to GeoTIFF format (the effect is equivalent to the inverse di
Unity3d 模型中心点的转换(源代码)
腾讯云服务器利用镜像部署WordPress个人网站!