Last active
October 2, 2017 11:38
-
-
Save qborreda/9f6aa3ab469af0906bafdb9abc1f5a71 to your computer and use it in GitHub Desktop.
Promisify a node function
This file contains hidden or 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
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]); | |
}) |
This file contains hidden or 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
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")) |
This file contains hidden or 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
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