[Javascript] Convert a Callback-Based JavaScript Function to a Promise-Based One
阿新 • • 發佈:2018-12-07
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); } );