July 2018
Beginner
100 pages
2h 7m
English
Promises are an alternative to callbacks for delivering the results of an asynchronous computation. First, let's look at the basic structure of promises, before we briefly look at the advantages of using promises over normal callbacks.
Let's rewrite the code above with promises:
const fs = require('fs');const readFile = (file) => { return new Promise((resolve, reject) => { fs.readFile(file, 'utf8', (err, data) => { if (err) reject(err); else resolve(data); }); });}// call the async functionreadFile(`${__dirname}/../temp/sample.txt`) .then(data => console.log(data)) .catch(error => console.log('err: ', error.message));
This code can further be simplified by using the util.promisify function, which takes a function following the ...
Read now
Unlock full access