我们先来看一下async函数是怎么使用的
const getData = (sec) => new Promise((resolve) => {setTimeout(() => resolve(sec * 2), sec * 1000);})// aim to get this asycnFun by generator
async function asyncFun() {const data1 = await getData(1);const data2 = await getData(data1);return data2;
}
// 可以看到asyncFun执行的返回结果是一个Promise,value为data2
// 3s后输出了4
asyncFun().then(console.log);
使用generator实现async函数
function* generatorFun() {const data1 = yield getData(1);const data2 = yield getData(2);return data2;
}// 将generator函数转换为async函数
function generator2Async(generatorFun) {// 返回async函数,该函数的返回值应为Promisereturn function() {const gen = generatorFun.apply(this, arguments);return new Promise((resolve, reject) => {function step(key, arg) {try {const {value, done} = gen[key](arg);if (done) {return resolve(value);} else {Promise.resolve(value).then((res) => step('next', res), err => step('throw', err));}} catch (err) {return reject(err);}}// executestep('next');})}
}const asyncFunFromGenrator = generator2Async(generatorFun);
asyncFunFromGenerator().then(console.log);