Node 8 added a promisify
function to the util core module. A couple of simple usage examples follow.
Usage with a promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {promisify} = require('util'); | |
const fs = require('fs'); | |
const readFile = promisify(fs.readFile); | |
readFile('./foo.txt').then( | |
fileContents => console.log(fileContents.toString()), | |
error => console.error(error) | |
); |
Usage with async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {promisify} = require('util'); | |
const fs = require('fs'); | |
const readFile = promisify(fs.readFile); | |
// await can only be used within an async function | |
(async () => { | |
try { | |
const fileContents = await readFile('./foo.txt'); | |
console.log(fileContents.toString()); | |
} catch (ex) { | |
ex => console.error(error) | |
} | |
})(); |
Multiple callback arguments
If the callback takes multiple arguments the promise will resolve to an object with a key/value for each argument.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {promisify} = require('util'); | |
const child = require('child_process'); | |
const exec = promisify(child.exec); | |
exec('echo "Hello world"').then( | |
result => console.log(result), // Prints { stdout: 'Hello world\n', stderr: '' } | |
error => console.error(error) | |
); |