支持Promise的Generator Runner

爲了更斜體文字好的理解生成器+Promise協同運做模式,本身自定義一個獨立工具run(..),它會自動異步運行傳遞給它的生成器,直到結束app

----------
Examples:
    // 把基於回調的代碼轉換爲基於Promise的代碼:
    if(!Promise.wrap) {
        Promise.wrap = function(fn) {
            return function() {
                var args = [].slice.call(arguments);
                return new Promise((resolve, reject) => {
                    fn.apply(null, args.concat(function(err, data) {
                        if(err) {
                            reject(err);
                        }else {
                            resolve(data);
                        }
                    }));
                });
            };
        };
    }
    
    function calc(x, y, cb) {
        var sum = x + y;
        if(sum < 10) {
            cb(null, sum);
        }else {
            cb(new Error("stack overflow"));
        }
    }
    
    // Generator Runner
    function run(gen) {
        var args = [].slice.call(arguments, 1);
        var it = gen.apply(this, args);
        return Promise.resolve().then(function handleNext(val) {
            var next = it.next(val);
            
            return (function handleResult(next) {
                if(next.done) {
                    return next.value;
                }else {
                    return Promise.resolve(next.value).then(handleNext, function handleError(err) {
                        return Promise.resolve(it.throw(err)).then(handleResult);
                    });
                }
            })(next);
        });
    }
    
    function* gen() {
        try {
            var res1 = yield Promise.wrap(calc)(1, 2);
            console.log("res1: ", res1);
            
            var res2 = yield Promise.wrap(calc)(5, 6);
            console.log("res2: ", res2);
        } catch(e) {
            console.error(e);
        }
        
        // 測試拋出異常後是否繼續執行
        var res3 = yield Promise.wrap(calc)(3, 4);
        console.log("res3: ", res3);
        
        return "the end";
    }
    
    run(gen).then(val => console.log(val), err => console.error(err));
console output:
res1:  3
Error: stack overflow(…)
res3:  7
the end
相關文章
相關標籤/搜索