Skip to content

Instantly share code, notes, and snippets.

@qborreda
Last active October 2, 2017 11:38
Show Gist options
  • Save qborreda/9f6aa3ab469af0906bafdb9abc1f5a71 to your computer and use it in GitHub Desktop.
Save qborreda/9f6aa3ab469af0906bafdb9abc1f5a71 to your computer and use it in GitHub Desktop.
Promisify a node function
let filenames = ['index.html', 'blog.html', 'terms.html'];
Promise.all(filenames.map(readFilePromise))
.then(files => {
console.log('index:', files[0]);
console.log('blog:', files[1]);
console.log('terms:', files[2]);
})
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(reject, ms);
})
}
/* Resolves with the first promise fulfilled */
Promise.race([readFilePromise('index.html'), timeout(1000)])
.then(data => console.log(data))
.catch(e => console.log("Timed out after 1 second"))
function readFilePromise(filename) {
return new Promise((resolve, reject) = > {
fs.readFile(filename, 'utf8', (err, data) = > {
if (err) reject(err);
else resolve(data);
})
})
}
readFilePromise('index.html')
.then(data = > console.log(data))
.catch (e = > console.log(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment