迭代器,生成器,async,await詳解

迭代器

這里先來做一個小的demo,假設(shè)要遍歷一個數(shù)組,拿到數(shù)組的元素,該怎么做,會敲代碼的肯定想到了循環(huán),有js基礎(chǔ)的肯定想到了for。of 方法,但是這些方法都不能很好的控制你要到哪一步,如果要精確的控制循環(huán)到哪一個步驟,循環(huán)的方法就有些吃力,這里就是迭代器要解決的問題,迭代器能夠很好的控制每一步驟的生成,下面做一個demo來控制步驟執(zhí)行

const names = ['asd', 'sd', 'reg', 'vdvs', 'fas'];  //遍歷的數(shù)組

let index = 0; 
const nameIterrator = { 
  next: function () {  //next迭代的方法,控制每一步驟的執(zhí)行
    if (index < names.length) {   // 數(shù)組沒有遍歷完進(jìn)入
     // 返回一個對象,對象中包含數(shù)組的元素和是否遍歷完成的信息
      return { done: false, value: names[index++] }; 
    }
    //遍歷完成,done表示遍歷完成,value的值為undefined
    return { done: true, value: undefined };
  },
};
console.log(nameIterrator.next()); //{ done: false, value: 'asd' }
console.log(nameIterrator.next());//{ done: false, value: 'sd' }
console.log(nameIterrator.next());//{ done: false, value: 'reg' }
console.log(nameIterrator.next());//{ done: false, value: 'vdvs' }
console.log(nameIterrator.next());//{ done: false, value: 'fas' }
console.log(nameIterrator.next());//{ done: true, value: undefined }

在上列中可以看到,沒調(diào)用一次next方法,數(shù)組往下遍歷一次,這樣就可以精確控制每一步驟的執(zhí)行,可以將上面的方法封裝為一個函數(shù),讓方法可以遍歷不同的數(shù)組

const name = ['asd', 'vds', 'fesd', 'tbb', 'wrew'];
const arr = [1, 5, 7, 2, 9, 6];
//迭代器函數(shù)
function createItertor(arr) {
  let index = 0;
  return {
    next() {
      if (index < arr.length) {
        return { done: false, value: arr[index++] };
      }
      return { done: true, value: undefined };
    },
  };
}
//創(chuàng)建不同的迭代函數(shù)
const Itertor = createItertor(name);
const Aitertor = createItertor(arr);
console.log(Itertor.next());
console.log(Itertor.next());
console.log(Itertor.next());
console.log(Itertor.next());
console.log(Itertor.next());
console.log(Itertor.next());

還可以來實(shí)現(xiàn)一個對象的迭代,我們都知道for of 是不能迭代對象的元素,但是有迭代器的話就可以將不能迭代的對象也能用for of 方法,這是因?yàn)閷ο蟮膬?nèi)部沒有實(shí)現(xiàn)[Symbol.iterator]方法,數(shù)組和字符串都實(shí)現(xiàn)了這個方法,所以只要在對象中也實(shí)現(xiàn)這個方法,那么對象就可以迭代了

const iterator = {
  names: ['asv', 'grs', 'rbt', 'fa'],
 //這里用了symbol的迭代器方法,每次for of 進(jìn)行遍歷的時候都會找這個方法
//只要是實(shí)現(xiàn)了 [Symbol.iterator]方法就可以迭代
  [Symbol.iterator]: function () { 
    let index = 0;
    return {
      next: () => {
        if (index < this.names.length) {
          return { done: false, value: this.names[index++] };
        } else {
          return { done: true, value: undefined };
        }
      },
    };
  },
};
const iterator1 = iterator[Symbol.iterator]();
console.log(iterator1.next()); //可以next方法
for (let item of iterator) {   //也可以用for of 方法
  console.log(item);
}

還可以實(shí)現(xiàn)一個類的迭代

class Room {
  constructor(stu) {
    this.stu = stu;
  }
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.stu.length) {
          return { done: false, value: this.stu[index++] };
        } else {
          return { done: true, value: undefined };
        }
      },
      //提前停止的方法
      return: () => {
        console.log('迭代器提前終止了');
        return { done: true, value: undefined };
      },
    };
  }
}
//類的內(nèi)部實(shí)現(xiàn)一個可迭代的方法
const room = new Room(['asd', 'asv', 'fvds']);
for (let item of room) {
  console.log(item);
  if (item === 'asv') break;
}

生成器

在上面的代碼中next函數(shù)的實(shí)現(xiàn)是迭代器的核心,但是每次都要手動實(shí)現(xiàn),生成器的出現(xiàn)就是為了更簡單的使用迭代器

//函數(shù)的后面接一個*,表示是一個生成器函數(shù)
function* foo() {
  console.log('start');

  let value1 = 200;
  console.log('1', value1);
  yield value1;  //yield表示,next在哪一行停止,可以理解為打了一個斷點(diǎn),用next執(zhí)行下一個斷點(diǎn)

  let value2 = 300;
  console.log('2', value2);
  yield value2;

  let value3 = 500;
  console.log('3', value3);
  yield value3;

  console.log('end');
  return 'end';
}

const fo = foo();
console.log(fo.next());  //{ value: 200, done: false }
//console.log(fo.next());
// console.log(fo.next());
// console.log(fo.next());

生成器的next還可以傳入?yún)?shù),傳入的參數(shù)在yeild的返回值中

function* foo(num) {
  console.log('start');
  const value1 = 100 * num;
  console.log('1', value1);
  const n = yield value1;

  const value2 = 200 * n;
  console.log('2', value2);
  const m = yield value2;

  const value3 = 300 * m;
  console.log('3', value3);
  try {
    const l = yield value3;
    console.log('yield返回值', l);
  } catch (error) {
    console.log(error);
  }

  const value4 = 200;
  console.log('4', value4);
  const t = yield value2;

  const value5 = 200 * t;
  console.log('5', value5);
  const k = yield value5;

  console.log('end');
}

const iterator = foo(10);
//next傳的參數(shù)在yield返回值中
console.log(iterator.next(5));
console.log(iterator.next(10));
console.log(iterator.next(20));
//return中止內(nèi)部的執(zhí)行,可以傳入?yún)?shù),在yield的返回值中,執(zhí)行本次yeild終止
//console.log(iterator.return(36));
//throw拋出異常,傳遞的參數(shù)可以在trycatch中接收錯誤信息中,在下一個yeild終止
console.log(iterator.throw('err message'));

可以用生成器來替代迭代器使用

//函數(shù)
function* iterator(arr) {
  //寫法一
  let index = 0;
  return {
    next: function () {
      if (index < arr.length) {
        return { done: false, value: arr[index++] };
      } else {
        return { done: true, value: undefined };
      }
    },
  };
  //寫法二
  for (const item of arr) {
    await item;
  }
  //寫法三:yeild* 后面跟上一個可迭代對象
  yield* arr;
}

//類
class Room {
  constructor(room) {
    this.room = room;
  }
  *[Symbol.iterator]() {
    yield* this.room;
  }
}

const room = new Room(['asv', 'fdev', 'ebrv', 'vds']);
for (let item of room) {
  console.log(item);
}

async await

在了解async await的原理之前,先來知道為什么要這個兩個關(guān)鍵字,我們都知道async await是用來做異步請求的,在沒有這個關(guān)鍵字前,異步的請求是怎么來實(shí)現(xiàn)的
先用setTimeout來模擬一下網(wǎng)絡(luò)請求,每次請求加上一個字符串

function requestData(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(url);
    }, 1000);
  });
}

回調(diào)調(diào)用

requestData('aaa').then((res) => {
   requestData(res + 'bbb').then((res) => {
     requestData(res + 'ccc').then((res) => {
     console.log(res);
     });
   });
 });

調(diào)用的次數(shù)一多的話,就會造成回調(diào)地獄,而且代碼也不夠簡潔

鏈?zhǔn)秸{(diào)用

requestData('aaa')
  .then((res) => {
    return requestData(res + 'bbb');
  })
  .then((res) => {
    return requestData(res + 'ccc');
  })
  .then((res) => {
    console.log(res);
  });

沒有回調(diào)地獄了,但是代碼不夠簡潔,次數(shù)一多的話還是有大量冗余代碼

promise + 生成器

function* getData() {
  const res1 = yield requestData('aaa');
  const res2 = yield requestData(res1 + 'bbb');
  const res3 = yield requestData(res2 + 'ccc');
  console.log(res3);
}

const generator = getData()
//調(diào)用next方法
generator.next().value.then(res => {
  generator.next(res).value.then(res => {
    generator.next(res).value.then(res => {
      generator.next(res)
    })
  })
})

這樣執(zhí)行的請求就非常的簡潔,但是需要手動來調(diào)用next方法,增加了額外的開銷,所以,為了解決這個額外的開銷,async await 就出來了,只需要在函數(shù)的前面加上async ,在要進(jìn)行請求語句前面加上await就可以實(shí)現(xiàn)異步請求了,還不用手動調(diào)用next方法,如果看懂了上面的代碼的話,這里就很好理解async await的原理了,這個其實(shí)就是promise加生成器的語法糖

async function getData() {
  const res1 = await requestData("why")
  const res2 = await requestData(res1 + "aaa")
  const res3 = await requestData(res2 + "bbb")
  const res4 = await requestData(res3 + "ccc")
  console.log(res4)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容