var fs = require('fs');
var readFile = function(fileName) {
return new Promise(function(resolve, reject) {
fs.readFile(fileName, function(error, data) {
resolve(data);
});
});
};
var asyncReadFile = async function() {
var f1 = await readFile('.../input.txt');
var f2 = await readFile('.../output.txt');
console.log(f1.toString());
console.log(f2.toString());
};
asyncReadFile();
//下面等效 async执行通过generator
// var gen = function*() {
// var f1 = yield readFile('.../input.txt');
// var f2 = yield readFile('.../output.txt');
// console.log(f1.toString());
// console.log(f2.toString());
// };
// 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);
还可以实现延时的promise,嵌套一个return new Promise
里面加setTimeout
但是函数要记得 直接包含的await一定要是async函数
var asyncReadFile = async function() {
return new Promise((resolve, reject) => {
setTimeout(async() => {
var f1 = await readFile('.../input.txt');
var f2 = await readFile('.../output.txt');
console.log(f1.toString());
console.log(f2.toString());
resolve("v")
}, 1000);
})
};
asyncReadFile().then(val => console.log(val));