async函数转为 generator 函数,并放入co自执行函数中运行,await就相当于generator函数中的 yield 执行器,执行一次promise 返回{value, done}

    1. function yieldPromise(generator){
    2. var iterator=generator();
    3. recursiveCore.call(iterator);
    4. }
    5. function recursiveCore(feedback){
    6. var iterator=this,
    7. result=iterator.next(feedback);
    8. if(result.done){
    9. return;
    10. }
    11. var promise=result.value;
    12. Promise.resolve(promise).then(function(v){
    13. recursiveCore.call(iterator,v);
    14. });
    15. }
    16. yieldPromise(function*(){
    17. var v1=yield new Promise(function(resolve,reject){
    18. setTimeout(function(){
    19. resolve('Hello');
    20. },1500);
    21. });
    22. console.warn(v1);
    23. var v2=yield new Promise(function(resolve,reject){
    24. setTimeout(function(){
    25. resolve('World');
    26. },1500);
    27. });
    28. console.warn(v2);
    29. });
    1. function yeildPromise(gen) {
    2. const iterator = gen()
    3. const next = data => {
    4. const { done, value } = iterator.next(data);
    5. if(done) return value;
    6. value.then(data => next(data))
    7. }
    8. next();
    9. }
    1. function asyncToGenerator(generatorFunc) {
    2. return function() {
    3. const gen = generatorFunc.apply(this, arguments)
    4. return new Promise((resolve, reject) => {
    5. function step(key, arg) {
    6. let generatorResult
    7. try {
    8. generatorResult = gen[key](arg)
    9. } catch (error) {
    10. return reject(error)
    11. }
    12. const { value, done } = generatorResult
    13. if (done) {
    14. return resolve(value)
    15. } else {
    16. return Promise.resolve(value).then(val => step('next', val), err => step('throw', err))
    17. }
    18. }
    19. step("next")
    20. })
    21. }
    22. }
    1. const obj = {a: 'a1', b: 'b1', c: 'c1'};
    2. // typeof obj[Symbol.iterator] // 'undefined'
    3. //
    4. // for (const val of obj) {
    5. // console.log(val);
    6. // }
    7. // VM974:4 Uncaught TypeError: obj is not iterable
    8. obj[Symbol.iterator] = function() {
    9. const self = this;
    10. const keys = Object.keys(this);
    11. const len = keys.length;
    12. let pointer = 0;
    13. return {
    14. next() {
    15. const done = pointer >= len;
    16. console.log('----', keys);
    17. const value = !done ? self[keys[pointer++]] : undefined;
    18. return {
    19. value,
    20. done
    21. };
    22. }
    23. }
    24. }
    25. for (const val of obj) {
    26. console.log('val', val);
    27. }
    28. // 'a1'
    29. // 'b1'
    30. // 'c1'