Created
March 24, 2016 08:13
-
-
Save fwon/f3b200d1761432e5e808 to your computer and use it in GitHub Desktop.
promise模式的异步自动执行
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
var fs = require('fs'); | |
var readFile = function (fileName){ | |
return new Promise(function (resolve, reject){ | |
fs.readFile(fileName, function(error, data){ | |
if (error) reject(error); | |
resolve(data); | |
}); | |
}); | |
}; | |
var gen = function* (){ | |
var f1 = yield readFile('/etc/fstab'); | |
var f2 = yield readFile('/etc/shells'); | |
console.log(f1.toString()); | |
console.log(f2.toString()); | |
}; | |
//手动启动 | |
var g = gen(); | |
g.next().value.then(function(data){ | |
g.next(data).value.then(function(data){ | |
g.next(data); | |
}); | |
}) | |
//自动执行方法 | |
function run(gen){ | |
var g = gen(); | |
function next(data){ | |
var result = g.next(data); | |
if (result.done) return result.value; | |
result.value.then(function(data){ | |
next(data); | |
}); | |
} | |
next(); | |
} | |
run(gen); | |
//参考co.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment