Last active
December 10, 2015 11:27
-
-
Save dijam/0f71e20917200e32981d to your computer and use it in GitHub Desktop.
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
var q = require('q'); | |
var fs = require('fs'); | |
function test() { | |
var deferred = q.defer(); | |
fs.readFile("package.json", "utf-8", function (error, text) { | |
if (error) { | |
deferred.reject(new Error(error)); | |
} else { | |
setTimeout(function() { | |
console.log('I am done! who is next?'); | |
deferred.resolve(text); | |
}, 1500); | |
} | |
}); | |
return deferred.promise; | |
} | |
function test2() { | |
var deferred = q.defer(); | |
test().then(deferred.resolve('before')); | |
return deferred.promise; | |
} | |
function test3() { | |
var deferred = q.defer(); | |
test().then(function () { | |
deferred.resolve('after'); | |
}); | |
return deferred.promise; | |
} | |
function test4() { | |
var deferred = q.defer(); | |
test().then(deferred.resolve); | |
return deferred.promise; | |
} | |
test2().then(function (data) { | |
console.log('This one calls ' + data + ' results coming'); | |
}); | |
test3().then(function (data) { | |
console.log('This one calls ' + data + ' results coming'); | |
}); | |
test4().then(function (data) { | |
console.log('This one calls after results with data from package.json ', data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've been using the
Pattern a lot until I read this: https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern
Now I try to avoid it, but I really don't know how to do that using Q. In private projects I use Bluebird which has a nice, terse syntax which I really like.
Do you know if you can do something similar in Q?