[Javascript] Convert a Callback-Based JavaScript Function to a Promise-Based One
2024-08-30 11:48:58
Sometimes, you might want to convert a JavaScript function that accepts a callback to one that returns a Promise
object. This lesson shows how to manually wrap a promise-based API around the fs.readFile()
function. It also explains how to use the util.promisify()
method that is built into the Node.js standard library.
const fs = require('fs') function readFile(path, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (error, contents) => {
if (error) {
reject(error)
} else {
resolve(contents)
}
})
})
} readFile(__filename, "utf8")
.then((contents) => {
console.log(contents)
}, error => {
console.error(error)
})
In nodejs we can use util function:
const fs = require("fs");
const util = require("util"); const readFile = util.promisify(fs.readFile); readFile(__filename, "utf8").then(
contents => {
console.log(contents);
},
error => {
console.error(error);
}
);
最新文章
- C语言中如何判断文件是否存在
- winfrom 隐藏任务栏(win7)
- Linux 改进捕捉信号机制(sigaction,sigqueue)
- POJ-2152 Fire (树形DP)
- HDU 4336-Card Collector(状压,概率dp)
- mht文件无法打开的解决办法
- 常用PC服务器LSI阵列卡配置
- HttpApplication事件执行顺序(转)
- unity3d插件Daikon Forge GUI 中文教程-5-高级控件listbox和progress bar的使用
- [Swust OJ 1132]-Coin-collecting by robot
- (Sqlyog或Navicat不友好处)SHOW ENGINE INNODB STATUS 结果为空或结果为=====================================
- Ubuntu 16.04 安装PCL库以及测试
- 安全之路 —— 使用Windows全局钩子打造键盘记录器
- springboot 传List参数
- linux shell中如何往所有行尾添加内容
- numpy.asmatrix的用法
- vue watch,computed,metods的区别
- iframe父页面获取iframe子页面的元素 与 iframe子页面获取父页面元素
- yum安装apache及问题解决
- HDU 1711 Number Sequence (KMP简单题)
热门文章
- 模块导入及使用,关键字,模块搜索路径,python文件的两种用途
- python面向对象(反射)(四)
- (原)UICollectionView的基本使用
- LeetCode(107) Binary Tree Level Order Traversal II
- nw335 debian sid x86-64 -- 5 使用xp的驱动
- python基础——12(包的概念)
- django的rest framework框架——认证、权限、节流控制
- POJ-3261 Milk Patterns,后缀数组+二分。。
- HackerRank# Red John is Back
- bzoj1411: [ZJOI2009]硬币游戏