SOURCE

var a = 1, b = 2;

// 1.普通函数
// function foo() {
//   a++;
//   b = b * a;
//   a = b + 3;
// }

// function bar() {
//   b--;
//   a = 8 + b;
//   b = a * 2;
// }

// a, b结果因foo, bar顺序不同只有两种结果
// foo();
// bar();
// bar();
// foo();

// 2.生成器
// function *foo(){
//   a++;
//   yield;
//   b*= a;
//   a = (yield b) + 3;
// }

// function *bar(){
//   b--;
//   yield;
//   a = (yield 8) + b;
//   b = a * (yield 2);
// }

// function step(gen) {
//   var last, it = gen();
//   return function(){
//     last = it.next(last).value;
//   }
// }

// var s1 = step(foo);
// var s2 = step(bar);

// // s1();
// // s1();
// // s1();
// // s2();
// // s2();
// // s2();
// // s2();

// s2(); // b--;
// s2(); // yield 8;
// s1(); // a++;
// s2(); // a = 8 + b; a = 9; yield 2;
// s1(); // b*=a; b = 9; yield b;
// s1(); // a = b + 3; a = 12;
// s2(); // b = a * 2; 
// // 问题来了 b = 24 or 18 ?

// console.log(a, b);

// 3. 模拟并发
const res=[]

function *reqData(url){
    const data=yield mockRequest(url)
    // 控制转移
    yield;
    res.push(data)
}


const it1=reqData('1')
const it2=reqData('2')

const p1=it1.next().value
const p2=it2.next().value

p1.then(data=>{
  	console.log('p1 data:', data);
    it1.next(data)
})

p2.then(data=>{
  console.log('p2 data:', data);
    it2.next(data)
})

Promise.all([p1,p2])
.then(()=>{
    it1.next()
    it2.next()
    console.log('res',res)
})

function mockRequest(data) { // 模拟异步请求
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            resolve(data)
        }, 50)
    })
}
console 命令行工具 X clear

                    
>
console