async await 的底层原理
示例
async function run() {
//await 等待的意恩,待局ose对象resolve时候的数据
let a = await read("./data/a.txt");
let b = await read("./data/b.txt");
let c = await read("./data/c,txt");
console.log(a, b, c);
}
run();
// 同下
function main() {
return co(function* () {
let a = yield read("./data/a.txt");
let b = yield read("./data/b.txt");
let c = yield read("./data/c.txt");
return { a, b, c };
});
}
main().then(data => {
console.log(data.a+ data.b+ data.c)
})
genetator + promise +co库 (生成器 执行)
const fs = require('fs')
// 使用 Promsie 完成 a.txt b.txt c.txt 顺序的读取
function read(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf-8', (error, data) => {
if (error) {
reject(error); // 失败
} else {
resolve(data)
}
})
})
}
// generator yield ,next
function* run() {
// yield 后面是一个Promise对象
let a = yield read('./data/a.txt');
let b = yield read('./data/b.txt');
let c = yield read(' ./data/c.txt');// console.Log(c,c的值');return a + b + c;
return a+b+c
}
// co的底层
/*自己实现一个 co库
1.参数是一个生成器函数
2.返回值是一个Promise对象
*/
function myco(generatorFn) {
const it = generatorFn(); // 进行迷归调用
return new Promise((resolve, reject) => {
function next(lastValue) {
let { value, done } = it.next(lastValue);
if (done) {
resolve(value); // 代表是完成了直接 resolve(value)
} else {
value.then(next, reject); // /生成器还没有执行完毕,
}
}
next();
})
}
myco(run).then(data => {
console.log(data);
})