[Javascript] Convert a Callback-Based JavaScript Function to a Promise-Based One
JavaScript to Function One Promise based convert callback
2023-09-14 08:59:16 时间
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); } );
相关文章
- [Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()
- [Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
- [Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)
- [Javascript] How to use JavaScript's String.replace
- [Javascript] What is JavaScript Function Currying?
- [Javascript] An Introduction to JSPM (JavaScript Package Manager)
- javascript运算符的优先级
- [Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()
- [Javascript] Write a Generator Function to Generate the Alphabet / Numbers
- [Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)
- [Javascript] Proper use of console.assert in JavaScript
- [Javascript] How to use JavaScript's String.replace
- [Javascript] An Introduction to JSPM (JavaScript Package Manager)
- [Javascript] Function Expression Ex, Changing Declarations to Expressions
- javascript面向对象之Javascript 继承
- Atitit 文件上传 架构设计 实现机制 解决方案 实践java php c#.net js javascript c++ python
- 使用 Promise 来改写 JavaScript 的加载逻辑
- SAP Server Side JavaScript解决方案
- javascript案例29——求1~100累加和,跳过个位数为3的数。
- web前端框架Javascript开发基础之JavaScript作用域