抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

原作者写的ts太乱了,看不懂,自己还原了个js版的

function next_step(action, gen, resolve, reject, args, _next, _throw) {
    try {
        const { value, done } = gen[action](args)
        if (done) {
            resolve(value)
        } else {
            Promise.resolve(value).then(_next, _throw)
        }
    } catch (error) {
        reject(error)
    }
}

function _async(fn) {
    return function (...args) {
        const self = this;
        return new Promise((resolve, reject) => {
            const gen = fn.apply(self, args);

            function _next(...nextArgs) {
                next_step('next', gen, resolve, reject, nextArgs, _next, _throw)
            }
            function _throw(...err) {
                next_step('throw', gen, resolve, reject, err, _next, _throw)
            }
            _next()
        })
    }

}
const asyncFunc = _async(function* (param) {
    try {
        yield new Promise((resolve, reject) => {
            setTimeout(() => {
                reject(param)
            }, 1000)
        })
    } catch (error) {
        console.log(error)
    }

    const a = yield 'a'
    const d = yield 'd'
    const b = yield Promise.resolve('b')
    const c = yield Promise.resolve('c')
    return [a, b, c, d]
})

asyncFunc('error').then((res) => {
    console.log(res)
})

  // error
  // ['a', 'b', 'c', 'd']

作者:Col0ring
链接:https://juejin.cn/post/6913393501262577672
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论