Created
October 25, 2013 05:20
-
-
Save huazhouji/7149751 to your computer and use it in GitHub Desktop.
learn Q
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.js'); | |
var FS = require('fs'); | |
// 方法1 defer | |
var deferred = Q.defer(); | |
FS.readFile("url.js", "utf-8", function (error, text) { | |
if (error) { | |
deferred.reject(new Error(error)); | |
} else { | |
deferred.resolve(text); | |
} | |
}); | |
deferred.promise | |
.then(function(text) { | |
console.log('Success: ' + text); | |
}, function(reason) { | |
console.log('Failed: ' + reason); | |
}, function(notice) { | |
console.log('Got notification: ' + notice); | |
}) | |
.then(function(){ | |
console.log("1"); | |
}).then(function(){ | |
console.log("2"); | |
}); | |
// 方法2 nfcall | |
Q.nfcall(FS.readFile, "helloworld.js", "utf-8") | |
.then(function(filec){ | |
console.log("content:" + filec); | |
},function(reason){ | |
console.log(reason); | |
}); | |
// 方法3 从node中构造promise | |
// return Q.ninvoke(redisClient, "get", "user:1:id"); | |
// return Q.npost(redisClient, "get", ["user:1:id"]); | |
var readFile = Q.denodeify(FS.readFile); | |
readFile("exists.txt", "utf-8") | |
.then(function(result){ | |
console.log("noerr:" + result); | |
},function(reason){ | |
console.log("err:" + reason); | |
}); | |
// var redisClientGet = Q.nbind(redisClient.get, redisClient); | |
// return redisClientGet("user:1:id"); | |
// var deferred = Q.defer(); | |
// FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver()); | |
// return deferred.promise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment