Last active
February 11, 2016 11:58
-
-
Save Lazhari/615952ef713e2ec51e96 to your computer and use it in GitHub Desktop.
ECMAScript 6 Promise for Node.js
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
const Article = require('./models/article'); | |
function getArticles(callback) { | |
callback = callback || function () {}; | |
return new Promise((resolve, reject) => { | |
Article.find({}, (err, articles) => { | |
if(err) { | |
reject(err); | |
return callback(err); | |
} | |
if(!articles) { | |
reject(new Error('No articles')); | |
return callback(new Error('No articles')); | |
} | |
resolve(articles); | |
return callback(null, articles); | |
}); | |
}); | |
} | |
getArticles().then((data) => { | |
console.log(data); | |
}, (err) => { | |
console.log(err.message); | |
}) |
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
'use strict'; | |
const fs = require('fs'); | |
function readPackage(callback) { | |
callback = callback || function () {}; | |
return new Promise((resolve, reject) => { | |
fs.readFile('./package.json', (err, data) => { | |
if(err) { | |
reject(err); | |
return callback(err); | |
} | |
resolve(data); | |
return callback(null, data); | |
}); | |
}); | |
} | |
readPackage().then((data) => { | |
console.log(data); | |
}, (err) => { | |
console.log(err.message); | |
}) | |
module.exports.readPackage = readPackage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment