Skip to content

Instantly share code, notes, and snippets.

@diablowu
Created June 16, 2016 15:42
Show Gist options
  • Save diablowu/2172fa33bbe027e18db4c461eb257678 to your computer and use it in GitHub Desktop.
Save diablowu/2172fa33bbe027e18db4c461eb257678 to your computer and use it in GitHub Desktop.
read 3 file with callback , Promise and generator
'use strict'
var co = require('co')
var fs = require('fs')
var cofs = require('co-fs')
var r1 = exports.r1 = function(fileName){
fs.readFile(fileName, (err,data)=>{
fs.readFile(data.toString().trim(), (err,data)=>{
fs.readFile(data.toString().trim(),(err,data)=>{
fs.readFile(data.toString().trim(), (err,data)=>{
console.log(data.toString())
})
})
})
})
}
function readFileQ(fileName){
return new Promise(
function(resolve, reject) {
fs.readFile(fileName, (err,data)=>{
if(!!err){
reject(err)
}else{
resolve(data.toString().trim())
}
})
}
)
}
var r2 = exports.r2 = function(fileName){
readFileQ(fileName).
then((d)=>{
return readFileQ(d)
}).
then((d)=>{
return readFileQ(d)
}).
then((d)=>{
return readFileQ(d)
}).
then((d)=>{
console.log(d)
})
}
var r3 = exports.r3 = function(fileName){
co(function*(){
var a = yield cofs.readFile(fileName)
var b = yield cofs.readFile(a.toString().trim())
var c = yield cofs.readFile(b.toString().trim())
var d = yield cofs.readFile(c.toString().trim())
console.log(d.toString().trim())
})
}
r1('./a')
r2('./a')
r3('./a')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment