Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

实现一个async函数 #33

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago

题目

function getNum(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(num + 1);
        }, 1000);
    });
}

function asyncToGenerator(generatorFunction) {
    // ...
}

let func = function* () {
    let f1 = yield getNum(1);
    let f2 = yield getNum(f1);
    console.log(f2);
};
asyncToGenerator(func)(); // 3
Rain120 commented 2 years ago
function asyncToGenerator(generatorFunction) {
    return function () {
        const gen = generatorFunction.apply(this, arguments);

        return new Promise((resolve, reject) => {
            function step(key, ...args) {
                let generatorResult = null;

                try {
                    generatorResult = gen[key](...args);
                } catch (e) {
                    return reject(e);
                }

                const {value, done} = generatorResult;

                if (done) {
                    resolve(value);
                } else {
                    return Promise.resolve(value).then(
                        val => step('next', val),
                        err => step('throw', err)
                    );
                }
            }

            step('next');
        });
    };
}