返回列表

转载:ES6之generator

默认分类 2016/09/18 03:54

代码示例1:

var a = function*() {
    var serverData1 = yield myAjax(100);
    console.log('status:%s', serverData1.status);
    var serverData2 = yield myAjax(serverData1.status);
    console.log('status:%s', serverData2.status);
};

var pp = 0;
function myAjax (sum) {
    pp += sum;
   setTimeout(()=>{
      alist.next({status: pp});     
  }, 2000);
}

var alist = a();
alist.next({status: 300});

代码示例2:

var genRunner = (GenFunc) => {
    return new Promise((resolve, reject) => {
        var gen = GenFunc();
        var innerRun = (val) => {
            var val = gen.next(val);
            // 如果已经跑完了,则resolve
            if (val.done) return resolve(val.value);
            // 继续promise
            if (val.value) {
                val.value.then( (data) => {
                    innerRun(data);
                });
            } else {
                innerRun(val.value);
            }
        }
        innerRun();
    });
};

var pp = 0;

var myAjax = (sum) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            pp += sum;
            resolve({
                status: pp
            });
        }, 3000)
    });
};

genRunner(function*() {
    var serverData1 = yield myAjax(100);
    console.log('status:%s', serverData1.status);
    var serverData2 = yield myAjax(serverData1.status);
    console.log('status:%s', serverData2.status);
}).then((message) => {
    console.log(message);
});